LeetCode:Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

刪除有序鏈表中重複的數值,一次遍歷,設置指針指定第一次出現的數值,一直到該數值消失(或者鏈表到頭),刪除中間的所有重複值。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null)return head;
        ListNode p=head,q=head;
        int num=head.val;
        while(p!=null)
        {
            if(p.val!=num && p!=q)
            {
                num=p.val;
                q.next=p;
                q=p;
                
            }
            p=p.next;
        }
        if(p!=q)q.next=null;
        return head;
    }
}



發佈了34 篇原創文章 · 獲贊 0 · 訪問量 9649
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章