Delete duplicate nodes in a linked list-Sword point offer

Source: Internet
Author: User

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
    1. 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
    2. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.