zoukankan      html  css  js  c++  java
  • 剑指56.删除链表中重复的结点

    题目描述

    在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
     

    思路

    思路1:双指针非递归法。本题目的关键是要考虑到多种测试用例,例如重复的结点位于链表头部、中间、尾部。

    思路2:递归法。

     

    ☆☆解法1.1

    public class Solution {
        public ListNode deleteDuplication(ListNode pHead) {
            if (pHead == null) return null;
            ListNode pre = null;
            ListNode cur = pHead;
            while (cur != null){
                if (cur.next != null && cur.val == cur.next.val){
                    while (cur.next != null && cur.val == cur.next.val){
                        cur = cur.next;
                    }
                    cur = cur.next;
                    if (pre == null){
                        pHead = cur;
                    }else{
                        pre.next = cur;
                    }
                }else{
                    pre = cur;
                    cur = cur.next;
                }
            }
            return pHead;
        }
    }

    ☆☆解法1.2(使用虚拟头节点)

    public class Solution {
        public ListNode deleteDuplication(ListNode pHead) {
            if (pHead == null || pHead.next == null){
                return pHead;
            }
            ListNode head = new ListNode(-1);
            head.next = pHead;
            ListNode pre = head;
            ListNode cur = head.next;
            while (cur != null){
                if (cur.next != null && cur.val == cur.next.val){
                    while (cur.next != null && cur.val == cur.next.val){
                        cur = cur.next;
                    }
                    cur = cur.next;
                    pre.next = cur;
                }else{
                    pre = pre.next;
                    cur = cur.next;
                }
            }
            return head.next; // 虚拟头节点的下一个才是真实头节点
        }
    }
  • 相关阅读:
    git使用
    Git常用命令梳理
    git fetch 更新远程代码到本地仓库
    理解RESTful架构
    漫谈五种IO模型(主讲IO多路复用)
    python 单下划线/双下划线使用总结
    闰秒导致MySQL服务器的CPU sys过高
    闰秒问题
    Java线上应用故障排查之一:高CPU占用
    ZooKeeper安装与配置
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/13620760.html
Copyright © 2011-2022 走看看