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


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


    解题思路

    注意题目给出的条件:排序的链表,因此如果存在重复结点,那么一定是连续的。根据上述条件,我们可以设置双指针,如果遇到重复结点,一个指针保存当前位置,另一个往前走,直到走完该段重复指针为止

    public class Solution {
        public ListNode deleteDuplication(ListNode pHead) {
            if (pHead == null || pHead.next == null) {
                return pHead;
            }
            ListNode head = new ListNode(0);
            head.next = pHead;
            // 当前结点的前一个结点
            ListNode pre = head;
            // 当前结点
            ListNode node= head.next;
            while(node != null){
            	// 当前结点与其下一个结点重复
                if(node.next != null && node.val == node.next.val){
                    // 则指针一直向移动
                    while(node.next != null && node.val == node.next.val){
                        node = node.next;
                    }
                    // 改变前后指针各自指向的结点
                    pre.next = node.next;
                    node = node.next;
                }else{
                    pre = pre.next;
                    node = node.next;
                }
            }
            return head.next;
        }
    }
    

  • 相关阅读:
    netty 服务端 启动阻塞主线程
    idea踩过的坑
    bat批量重命名
    图片上传
    TCP/IP入门指导
    CPU governor调节器汇总
    IT咨询顾问:一次吐血的项目救火
    python 数组
    Python字符串
    基于Python实现对各种数据文件的操作
  • 原文地址:https://www.cnblogs.com/Yee-Q/p/14152726.html
Copyright © 2011-2022 走看看