文章目录
  1. 1. Remove Linked List Elements
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

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

思路

把结点值不等于val的结点加入链表中

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode dummy=ListNode(-1);
dummy.next=head;
ListNode *pre=&dummy,*cur=head;
while(cur){
if(cur->val==val){
cur=cur->next;
}
else{
pre->next=cur;
cur=cur->next;
pre=pre->next;
}
}
pre->next=NULL;
return dummy.next;
}
};

python版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
# @param {ListNode} head
# @param {integer} val
# @return {ListNode}
def removeElements(self, head, val):
dummy=ListNode(0)
dummy.next=head
pre=dummy
cur=head
while(cur):
if cur.val==val:
cur=cur.next
else:
pre.next=cur
cur=cur.next
pre=pre.next
pre.next=None
return dummy.next
文章目录
  1. 1. Remove Linked List Elements
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题