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

LeetCode OJ :Remove Linked List Elements (移除链表元素)

时间:2015-10-04 23:32:23      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

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

ps:这一题感觉没什么技巧可言,选取一个头指针,一个当前指针,一个前向指针。简单的链表操作而已,代码如下:

 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     ListNode* removeElements(ListNode* head, int val) {
12         ListNode * root = head;
13         ListNode * prev = head;
14         ListNode * curr = head;
15         while (curr != NULL){
16             if (curr->val == val){
17                 if (prev == curr)
18                     root = prev = curr = curr->next;
19                 else{
20                     curr = curr->next;
21                     prev->next = curr;
22                 }
23             }else{
24                 prev = curr;
25                 curr = curr->next;
26             }
27         }
28         return root;
29     }
30 };

 

LeetCode OJ :Remove Linked List Elements (移除链表元素)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4855151.html

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