您的位置:首页 > 其它

203 Remove Linked List Elements

2016-02-05 18:58 513 查看
题目链接:https://leetcode.com/problems/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 的结点删除即可。

需要注意的是一些特别的情况。

例如:

1. 要删除的结点在链表头。使用 while 循环,使 head 定位到第一个不用删除的结点上。

2. 要删除的结点在链表尾。同过 while(q != null) 来控制

3. 整个链表的结点都是需要删除的结点。

小技巧:在头结点之前再创建一个结点,这样就能将删除第一个结点的情况归为一般情况。

代码实现:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null)
return head;
while(head != null && head.val == val)
head = head.next;
if(head == null || head.next == null)
return head;
ListNode p = head;
ListNode q = head.next;
while(q != null) {
if(q.val == val) {
ListNode tmp = q;
q = q.next;
p.next = q;
} else {
p = p.next;
q = q.next;
}
}
return head;
}
}


63 / 63 test cases passed.
Status: Accepted
Runtime: 2 ms


方法二:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode helper = new ListNode(0);
helper.next = head;
ListNode p = helper;

while(p.next != null){
if(p.next.val == val){
ListNode next = p.next;
p.next = next.next;
}else{
p = p.next;
}
}

return helper.next;
}
}


63 / 63 test cases passed.
Status: Accepted
Runtime: 2 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: