《劍指 Offer》——刪除鏈表中重複的結點

1. 本題知識點

鏈表

2. 題目描述

在一個排序的鏈表中,存在重複的結點,請刪除該鏈表中重複的結點,重複的結點不保留,返回鏈表頭指針。 例如,鏈表 1->2->3->3->4->4->5 處理後爲 1->2->5

3. 解題思路

直接看代碼吧,由於使用了遞歸,難以解釋清楚。

4.代碼

 public class ListNode {
     int val;
     ListNode next = null;

     ListNode(int val) {
         this.val = val;
     }

     // 添加新的結點
     public void add(int newval) {
         ListNode newNode = new ListNode(newval);
         if (this.next == null)
             this.next = newNode;
         else
             this.next.add(newval);
     }

     // 打印鏈表
     public void print() {
         System.out.print(this.val);
         if (this.next != null) {
             System.out.print("-->");
             this.next.print();
         } else {
             System.out.println();
         }
     }
 }
public class Solution {

    /**
     * 刪除鏈表中重複的結點
     *
     * @param pHead
     * @return
     */
    public ListNode deleteDuplication(ListNode pHead) {
        // 如果當前結點爲空,或當前結點沒有後繼結點,則直接返回當前結點
        if (pHead == null || pHead.next == null) {
            return pHead;
        }
        // next 爲後繼結點
        ListNode next = pHead.next;
        // 如果當前結點不等於後繼結點
        if (pHead.val != next.val) {
            pHead.next = deleteDuplication(pHead.next);
            return pHead;
        }
        // 如果當前結點等於後繼結點
        else {
            while (next != null && pHead.val == next.val) {
                next = next.next;
            }
            return deleteDuplication(next);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章