您的位置:首页 > 职场人生

面试题57:删除链表中重复的结点

2017-07-16 16:51 477 查看
算法思想:方法一,递归实现。

public class Solution {
    public ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null || pHead.next == null) { // 只有0个或1个结点,则返回
            return pHead;
        }
        if (pHead.val == pHead.next.val) { // 当前结点是重复结点
            ListNode pNode = pHead.next;
            while (pNode != null && pNode.val == pHead.val) {
                // 跳过值与当前结点相同的全部结点,找到第一个与当前结点不同的结点
                pNode = pNode.next;
            }
            return deleteDuplication(pNode); // 从第一个与当前结点不同的结点开始递归
        } else { // 当前结点不是重复结点
            pHead.next = deleteDuplication(pHead.next); // 保留当前结点,从下一个结点开始递归
            return pHead;
        }
    }
}
算法思想:把当前结点的前一个结点(pre)和后面值比当前结点的值要大的结点相连。
public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead == null || pHead.next == null) return pHead;
        ListNode temp = new ListNode(-1);
        temp.next = pHead;
        ListNode curNode = pHead;
        ListNode pre = temp;
         while(curNode != null && curNode.next != null){
            ListNode next = curNode.next;
            if(curNode.val == next.val){
                while(next != null && curNode.val == next.val){
                    next = next.next;
                }
                pre.next = next;
                curNode = next;
            }else{
                pre = curNode;
                curNode = curNode.next;
            }
        }
        return temp.next;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: