LeetCode203—移除链表元素(java版)

题目描述:

标签:链表

删除链表中等于给定值 val 的所有节点。

  代码:

思路分析:哨兵节点,伪头结点

1、定义一个哨兵节点sentinel,值为0,next指向head;

2、定义一个前驱指针prev和当前指针cur,让prev指向哨兵节点,cur指向头结点,遍历链表有下面两种情况:

如果cur.val = val,删除结点,即prev.next = cur.next;

否则,让前驱结点后移 pre = cur

同时 cur = cur.next

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

        ListNode prev = sentinel;
        ListNode cur = head;
        while(cur != null){
            if(cur.val == val){
                prev.next = cur.next;
            }else{
                prev = cur;
            }
            cur = cur.next;
        }
        return sentinel.next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40840749/article/details/114409933
今日推荐