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

来源:互联网 发布:飞跃淘宝店铺信息软件 编辑:程序博客网 时间:2024/05/23 02:22

算法思想:方法一,递归实现。

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;    }}


阅读全文
0 0
原创粉丝点击