zoukankan      html  css  js  c++  java
  • 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时,删除完第一个节点,剩下的链表的头节点又是待删除节点。

  • 相关阅读:
    Linux产生coredump文件(core)
    shell脚本每五分钟执行一次可执行程序(nohup)
    VIM快捷操作
    日期正则表达式
    istringstream字符串流对象
    json和pickle模块
    sys模块
    random模块
    time模块
    python的模块
  • 原文地址:https://www.cnblogs.com/jiameng991010/p/11260241.html
Copyright © 2011-2022 走看看