Leetcode 203. Remove Linked List Elements

203. Remove Linked List Elements

  • Total Accepted: 71491
  • Total Submissions: 242394
  • Difficulty: Easy

 

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

 

思路:还是和以往一样,遇到等于val的,直接删除,但是要注意链表操作和数组操作删除操作的不同。

 

代码:

递归做法:比较巧妙,慢慢会适应。

 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         if(head==NULL) return NULL;
13         head->next=removeElements(head->next,val);
14         return head->val==val?head->next:head;
15     }
16 };

 

非递归做法:

 1 class Solution {
 2 public:
 3     ListNode* removeElements(ListNode* head, int val) {
 4         ListNode *front=new ListNode(val),*end;
 5         front->next=head;
 6         end=head;
 7         head=front;
 8         while(end){
 9             if(end->val==val){
10                 front->next=end->next;
11             }
12             else{
13                 front=end;
14             }
15             end=front->next;
16         }
17         return head->next;
18     }
19 };
posted @ 2016-07-17 20:40  Deribs4  阅读(133)  评论(0编辑  收藏  举报