木落长安rr

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

本题的思路很简单,就是单纯的删除链表元素操作,如果头结点的元素就是给定的val值,需要借助虚结点dummy去判断。

方法一:(C++) C++中注意结点的释放

 

 1 ListNode* removeElements(ListNode* head, int val) {
 2         ListNode* dummy=new ListNode(-1),* pre=dummy;
 3         pre->next=head;
 4         while(pre->next){
 5             if(pre->next->val==val){
 6                 ListNode* t=pre->next;
 7                 pre->next=pre->next->next;
 8                 t->next=NULL;
 9                 delete t;
10             }
11             else
12                 pre=pre->next;
13         }
14         return dummy->next;
15     }

 

Java:

 1 public ListNode removeElements(ListNode head, int val) {
 2         if(head==null||(head.next==null&&head.val==val))
 3             return null;
 4         ListNode dummy=new ListNode(-1),cur=dummy;
 5         cur.next=head;
 6         while(cur.next!=null){
 7             if(cur.next.val==val)
 8                 cur.next=cur.next.next;
 9             else
10                 cur=cur.next;
11         }
12         return dummy.next;
13     }

方法二:不使用虚结点的话,最后只需要再判断一下头结点的值是否符合要求(C++)

 1 ListNode* removeElements(ListNode* head, int val) {
 2         if(head==NULL)
 3             return head;
 4         ListNode* cur=head;
 5         while(cur->next){
 6             if(cur->next->val==val)
 7                 cur->next=cur->next->next;
 8             else 
 9                 cur=cur->next;
10         }
11         return (head->val==val)?head->next:head;
12     }

 

posted on 2019-03-29 15:13  木落长安rr  阅读(148)  评论(0编辑  收藏  举报