【LintCode】删除链表中的元素

时间:2023-03-10 03:42:39
【LintCode】删除链表中的元素

【LintCode】删除链表中的元素

问题分析:

声明当前指针和上一个指针即可。

问题求解:

public class Solution {

    public ListNode removeElements(ListNode head, int val) {
ListNode preListNode = new ListNode(0);// 上一个指针
ListNode nowListNode = head;// 当前指针
ListNode returnListNode = null;// 需要返回的链表
preListNode.next = nowListNode;
while (nowListNode != null) {
if (nowListNode.val == val) {
preListNode.next = nowListNode.next;
nowListNode = nowListNode.next;
} else {
preListNode = nowListNode;
nowListNode = nowListNode.next;
if (returnListNode == null) {
returnListNode = preListNode;
}
}
}
return returnListNode;
}
} class ListNode {
int val;
ListNode next; ListNode(int x) {
val = x;
}
}