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

删除链表中的元素

时间:2016-03-16 17:14:40      阅读:348      评论:0      收藏:0      [点我收藏+]

标签:

删除链表中等于给定值val的所有节点。

给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5

 

迷惑点:陷入没有表头的陷阱,总是想记下删除节点的先驱,导致折腾了很久,其实只要人为加一个表头就简单很多了!!

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     /**
12      * @param head a ListNode
13      * @param val an integer
14      * @return a ListNode
15      */
16     ListNode *removeElements(ListNode *head, int val) {
17         // Write your code here
18         //meiyou ya ba jie dian!!!???  自己加一个表头
19         //static int cnt = 0;
20         //kong biao!!就不是问题了。
21         ListNode *temp=new ListNode(0);
22         temp->next= head;
23         head=temp;
24         
25         while(head->next != NULL){
26             if(head->next->val == val){
27                 head->next = head->next->next;
28             }else{
29                 head = head->next;
30             }
31         }
32         return temp->next;
33 
34     }
35 };

 

删除链表中的元素

标签:

原文地址:http://www.cnblogs.com/Qwells/p/5283711.html

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