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; // 虚拟头节点的下一个才是真实头节点
        }
    }
  • 相关阅读:
    androidstudio配置模拟器路径
    Linux常见命令
    逆向助手使用
    Git服务器回滚到固定版本
    Git使用
    使用本地Gradle版本
    系统模拟器创建
    AndroidStudio设置代理
    关联、参数化、思考时间、检查点、事务的设置方式
    SQL:内连接、左外连接、右外连接、全连接、交叉连接区别
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/13620760.html
Copyright © 2011-2022 走看看