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