LeetCode 203——移除链表(JAVA)

删除链表中等于给定值 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) 
    {
        while(head!=null&&head.val==val)//初始化
        {
            ListNode pre=head;
            head=pre.next;
            pre.next=null;
        }
        if(head==null)//头节点为空
        {
            return null;
        }
        ListNode pre=head;
        while(pre.next!=null)
        {
            ListNode cur=pre.next;
            if(cur.val==val)//移除节点
            {
                pre.next=cur.next;
                cur.next=null;
            }
            else //指针后移
            {
                pre=pre.next;
            }
        }
       return head;
    }
} 

遍历链表,找出每个待删除节点前的每一个节点。

特殊情况:第一个节点就是待删除节点,要进行单独的操作。

注意点:当输入1->1时,删除完第一个节点,剩下的链表的头节点又是待删除节点。

猜你喜欢

转载自www.cnblogs.com/jiameng991010/p/11260241.html