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

删除链表中重复的结点(剑指offer)

时间:2019-04-16 00:58:54      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:div   while   else   nbsp   let   存在   scribe   delete   return   

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
方法一:递归
两种情况,如果是重复结点怎么办?遇到了就跳过,返回重复节点的下一个结点。
遇到不重复结点?遇到不重复结点直接连上。
/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public ListNode deleteDuplication(ListNode pHead) {
        if(pHead==null||pHead.next==null) return pHead;
        if(pHead.val==pHead.next.val){
            ListNode pNode=pHead;
            while (pNode!=null && pNode.val==pHead.val){
                pNode=pNode.next;
            }
            return deleteDuplication(pNode);
        }else {
            pHead.next=deleteDuplication(pHead.next);
            return pHead;
        }
    }
}

 

删除链表中重复的结点(剑指offer)

标签:div   while   else   nbsp   let   存在   scribe   delete   return   

原文地址:https://www.cnblogs.com/shaer/p/10714153.html

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