【剑指Offer学习】【题56:删除链表中重复的结点】

    xiaoxiao2022-07-02  107

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

    思路: 利用递归的方式,依次进行判断

    程序:

    class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class subject56 { public static ListNode deleteDuplication(ListNode pHead) { if(pHead == null || pHead.next == null) { return pHead; } ListNode first = pHead; ListNode second = pHead.next; if(first.val == second.val) {//first是重复结点 second = second.next; while(second != null && first.val == second.val) { second = second.next; } first = second; return deleteDuplication(first);//递归 }else {//first不是重复结点 first.next = deleteDuplication(second);//选择不是重复结点的结点作为下一个结点 return first; } } public static void main(String args[]) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(3); ListNode node5 = new ListNode(4); ListNode node6 = new ListNode(4); ListNode node7 = new ListNode(5); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node5.next = node6; node6.next = node7; ListNode temp = deleteDuplication(node1); while(temp != null) { System.out.println(temp.val); temp = temp.next; } } }
    最新回复(0)