Delete Duplicate node title description in linked list
In a sorted list, there are duplicate nodes, delete the duplicate nodes in the linked list, duplicate nodes are not retained, and return the chain header pointers. For example, the list 1->2->3->3->4->4->5 is treated as 1->2->5
Ideas
- Requires two pointers, one pointing to the previous node Prenode, the other pointing to the current node, and node moving backwards if it encounters equal nodes, Prenode, Save Node.val convenient to the back of the comparison, until the encounter node and Node.next is not equal, Prenode can point to Node.next
- Note: The beginning of the list of links may start with duplicate nodes, so the default Prenode=null, in the subsequent assignment to Prenode, if Prenode is null, then set Phead to Node.next
Code
/* 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) {return null;} ListNode prenode = null; ListNodeNode = Phead;while (Node ! = null) {if (Node.Next! = NULL &&Node.val = =Node.Next.val) {int value =Node.val;while (node. next! = null && node. next.val = = value) {node = Node.next;} if (Prenode = = null) {Phead = node. next;} else {prenode.next = node. next;} else {Prenode = node;} node = Span class= "Hljs-keyword" >node. next;} return phead; }}
Delete duplicate nodes in a linked list-Sword point offer