码迷,mamicode.com
首页 > 其他好文 > 详细

[剑指offer]删除链表中重复的结点

时间:2019-10-09 19:22:56      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:保留   public   subject   code   second   cond   nbsp   list   tps   

题目描述

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

 

题目链接:
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&tqId=11209&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

 

 

 

 

 

package com.sunshine.OFFER66_SECOND;

import org.junit.Test;

public class A56_deleteDuplication {


    @Test
    public void test() {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(1);
        ListNode n3 = new ListNode(2);
        ListNode n4 = new ListNode(3);
        ListNode n5 = new ListNode(3);
        ListNode n6 = new ListNode(4);
        ListNode n7 = new ListNode(5);
        ListNode n8 = new ListNode(5);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        n6.next = n7;
        n7.next = n8;
        ListNode pos = n1;
        while (pos != null) {
            System.out.print(pos.val + "->");
            pos = pos.next;
        }
        System.out.println();
        ListNode listNode = deleteDuplication(n1);
        pos = listNode;
        while (pos != null) {
            System.out.print(pos.val + "->");
            pos = pos.next;
        }
    }
    //其他人解
    public ListNode deleteDuplication(ListNode pHead) {
        if (null == pHead || null == pHead.next) {
            return pHead;
        }
        ListNode pre = new ListNode(0);
        ListNode ans = pre;
        pre.next = pHead;
        ListNode cur = pHead;
        while (cur != null) {
            if (cur.next != null && cur.next.val == cur.val) {
                while (cur.next != null && cur.next.val == cur.val) {
                    cur = cur.next;
                }
                cur = cur.next;
                pre.next = cur;
            } else {
                pre = cur;
                cur = cur.next;
            }
        }
        return ans.next;
    }
}

 

[剑指offer]删除链表中重复的结点

标签:保留   public   subject   code   second   cond   nbsp   list   tps   

原文地址:https://www.cnblogs.com/MoonBeautiful/p/11643543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!