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.

這是第一道完全在web中寫並且提交通過的題目。

跟之前的那道排序數組中消去一樣的數字是一個意思。但是用鏈表操作就容易多了。

忽略掉中間相等的直接拼接到不相等的那個元素過去就ok了。

上代碼

/**
 * 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;
        int nowValue=head.val;
        ListNode nowPoint=head;
        ListNode pointer=head;
        for(int indexList=0;pointer!=null;pointer=pointer.next){
            if(nowPoint.val==pointer.val){
                nowPoint.next=pointer.next;
            }else{
                nowPoint=pointer;
            }
        }
        return head;
    }
}


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