leetcode203-移除链表的元素 中文链表: https://leetcode-cn.com/problems/remove-linked-list-elements/description/ 英文链接: https://leetcode.com/problems/remove-linked-list-elements/description/ 分类:链表
删除链表中等于给定值 val 的所有节点。 示例: 输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
思路
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
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)
return head;
ListNode temp = head.next;
ListNode pre = head;
while(temp != null)
{
if(temp.next == null)
{
if(temp.val != val)
break;
pre.next = null;
break;
}
if(temp != null && temp.val == val)
{
int value = temp.next.val;
temp.val = value;
temp.next = temp.next.next;
}else
{
pre = temp;
temp = temp.next;
}
}
return head;
}
}
代码讲解