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时,删除完第一个节点,剩下的链表的头节点又是待删除节点。

  • 相关阅读:
    iOS 十六进制字符串 "#FFFF00" 转换成颜色对象
    iOS toast 的连续显示
    文件管理
    pod 常用命令
    键盘事件
    iOS 添加阴影
    渐变色
    Ubuntu安装flameshot截图工具
    Ubuntu安装酸酸乳客户端
    Ubuntu安装网易云音乐
  • 原文地址:https://www.cnblogs.com/jiameng991010/p/11260241.html
Copyright © 2011-2022 走看看