Delete duplicate nodes in a linked list

Source: Internet
Author: User

Because this program is getting tired of me, the details are troublesome.
Package Solutions;

Import java.util.ArrayList;

/**
* Created by Hu on 2015/12/12.
*/
/*
* Delete duplicate nodes in a linked list
* In a sort of linked list, there are duplicate nodes,
* Please delete the duplicate nodes in the linked list, duplicate nodes are not retained, return the linked table head pointer.
* For example, the list 1->2->3->3->4->4->5 treated as 1->2->5
*
* */
public class Solution32 {
public static ListNode deleteduplication (ListNode phead)
{
If the phead is empty or if there is only one node, then the head node is returned.
if (phead==null| | Phead.next==null) {
return phead;
}
P is the node traversing the linked list
ListNode P=phead.next;
ListNode Pre=phead;
ListNode Q=p.next;
while (Q!=null) {
if (p.val==q.val) {
Q=q.next;
}else {
if (p.next==q) {
Pre=p;
p=q;
Q=q.next;
}else if (p.next!=q) {
if (pre.val==p.val) {
return deleteduplication (q);
}
pre.next=q;
p=q;
Q=q.next;
}
}
}
if (p.next!=null) {
if (phead.val==p.val) {
return null;
}else {
Pre.next=null;
}
}
if (phead.val==phead.next.val) {
Phead=phead.next.next;
}
return phead;
}
public static void Main (string[] args) {
ListNode node1=new ListNode (1);
ListNode node2=new ListNode (1);
ListNode node3=new ListNode (2);
ListNode node4=new ListNode (3);
ListNode node5=new ListNode (3);
ListNode node6=new ListNode (4);
ListNode node7=new ListNode (5);
ListNode node8=new ListNode (5);
Node1.next=node2;
Node2.next=node3;
Node3.next=node4;
NODE4.NEXT=NODE5;
Node5.next=node6;
Node6.next=node7;
Node7.next=node8;
ListNode Res=node1;
ListNode res=deleteduplication (Node1);
while (Res!=null) {
System.out.print (res.val+ "");
Res=res.next;
}
}
}

Delete duplicate nodes in a linked list

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.