Remove Linked List Elements
Total
Accepted: 11291 Total
Submissions: 42824
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
Credits:
Special thanks to for adding this problem and creating all test cases.
翻译:移除一个整型链表中值为val的所有元素
解题思路:类似指针,一个前节点 preNode, 一个当前节点curNode ,当遇到值为val的节点时, 前节点preNode的下一节点直接指向当前节点 curNode的下一节点,即跳过值为val的节点 preNode.next=curNode.next 。
代码如下
/** * 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 temp = new ListNode(0); temp.next=head; ListNode preNode=temp;//设置前节点为空 ListNode curNode=head;//设置当前节点为头节点 while (curNode!=null) { if (curNode.val==val) { preNode.next=curNode.next; } else { preNode=preNode.next; } curNode=curNode.next; } return temp.next; } }
时间: 2024-10-19 19:36:09