码迷,mamicode.com
首页 > 其他好文 > 详细

Dummy Head在链表中的应用

时间:2017-04-16 12:35:35      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:else   有用   remove   应用   lin   integer   head   头结点   int   

Leetcode 203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

 

public ListNode removeElements(ListNode head,int val){

   ListNode dummyHead=new ListNode(-1);

   dummyHead.next=head;

   ListNode curr=head,prev=dummyHead;

   while(curr!=null){

     if(curr.val=val) prev.next=curr.next;

     else prev=prev.next;

     curr=curr.next;

     }

     return dummyHead.next;

 

}

 

Dummy Head是一种非常有用的技巧,容易写出bug free的code。本题中如果不用dummy head而直接返回head的话,就会存在要考虑head是否为空的问题,在while循环中会出现问题。有了dummyhead, 所有的节点都拥有了前置节点,也就不用再考虑头结点为空的情况了,这一点在删除节点是非常有用。返回时返回dummyhead.next,所以也不用存储头结点

Dummy Head在链表中的应用

标签:else   有用   remove   应用   lin   integer   head   头结点   int   

原文地址:http://www.cnblogs.com/shixueyuan/p/6718153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!