[offer-56] Delete duplicate nodes from the list
- Examination Points: Link List
- Time limit: 1 second
- Space limitation: 32768K
- In a sorted list, there are duplicate nodes. Please delete the duplicate nodes in the list. The duplicate nodes are not reserved and return to the header pointer of the list. For example, the chain table 1 - > 2 - > 3 - > 3 - > 4 - > 4 - > 5 is treated with 1 - > 2 - > 5.
- Have you made it yourself?
- Time:
Train of thought:
First, add a header node to facilitate the first and second nodes in the same situation.
2. Set the pre, last pointer, and the pre pointer to the node that is currently determined not to duplicate, while the last pointer is equivalent to the working pointer, searching all the way back.
Code:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } */ public class Solution { public ListNode deleteDuplication(ListNode pHead) { // Only 0 or 1 node if (pHead == null || pHead.next == null) { return pHead; } ListNode Head = new ListNode(0); Head.next = pHead; // Create a new header node ListNode pre = Head; // New Head Node ListNode last = Head.next; // Current pHead while (last != null) { // The value of the working node is the same as that of the next node. if (last.next != null && last.val == last.next.val) { // Find the last identical node while (last.next != null && last.val == last.next.val) { last = last.next; } // last.next is different pre.next = last.next; // next pointer continues to move backwards last = last.next; } else { // Separate movement pre = pre.next; last = last.next; } } // Return to the real header node return Head.next; } }
My question:
- It is possible to delete duplicates from the beginning of the node, so create a new node to save the header node.
- You need to find the nodes that are repeating all the time, so the last node starts traversing until you find the next one that is different, so the last.next node is new and not repetitive.
Other ideas 1:
Recursive code:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } */ public class Solution { public ListNode deleteDuplication(ListNode pHead) { // Only 0 or 1 node if (pHead == null || pHead.next == null) { return pHead; } // The current node is a duplicate node if (pHead.val == pHead.next.val) { ListNode node = pHead.next; while (node != null && node.val == pHead.val) { // Skip all nodes with the same value as the current node and find the first node that is different from the current node. node = node.next; } return deleteDuplication(node); // Recursion begins at the first node that is different from the current node } else { pHead.next = deleteDuplication(pHead.next); // Keep the current node and recurse from the next node return pHead; } } }