題目描述
在一個排序的鏈表中,存在重複的結點,請刪除該鏈表中重複的結點,重複的結點不保留,返回鏈表頭指針。 例如,鏈表1->2->3->3->4->4->5 處理後爲 1->2->5
這個題目需要自己分析刪除的過程:注意兩點:一個是不能中間斷開,再一個就是頭結點是null的情況。
如何不保證斷鏈:分前驅結點和當前結點和下一個結點。三個進行移動操作;
在線編程:
package TestMyselfe;
public class Test57 {
public static class ListNode {
int value;
ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.value = val;
}
@Override
public String toString() {
return value + "";
}
}
public static ListNode deleteDuplication(ListNode pHead)
{
if(pHead==null){
return null;
}
// //如果頭結點和下一個結點一樣重複【多餘】
// if(pHead.value==pHead.next.value){
// return null;
// }
//只有一個結點
if(pHead.next==null){
return pHead;
}
//創建一個新的鏈表空間
ListNode root = new ListNode();
root.next = pHead;
ListNode node=pHead;//當前結點
ListNode prenode=root;//前驅結點
while(node!=null&& node.next!=null){
// 有重複結點,與node值相同的結點都要刪除
if(node.value==node.next.value){
// 找到下一個不同值的節點,注意其有可能也是重複節點
while (node.next != null && node.next.value == node.value) {
node = node.next;//node傳遞到最後一個重複結點的地方
}
// 指向下一個節點,prev.next也可能是重複結點
// 所以prev不要移動到下一個結點
prenode.next=node.next;//也就是2-->4的意思
}else{
// 相鄰兩個值不同,說明node不可刪除,要保留
prenode.next=node;
prenode=prenode.next;
}
//鏈表的結點一直走
node=node.next;
}
return root.next;
}
// 1->2->3->3->4->4->5
private static void test01() {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(3);
ListNode n5 = new ListNode(4);
ListNode n6 = new ListNode(4);
ListNode n7 = new ListNode(5);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n6.next = n7;
ListNode result = deleteDuplication(n1);
print(result);
}
private static void print(ListNode head) {
while (head != null) {
System.out.print(head + "->");
head = head.next;
}
System.out.println("完美結束");
}
public static void main(String[] args) {
test01() ;
}
}