Remove Duplicates from Sorted List ---Leetcode 我的java題解

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.

 我的java題解

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {

//我的解法。 head頭指針不能動。需要另外創建一個index來移動,便於刪除重複的數據。


    public ListNode deleteDuplicates(ListNode head) {
          ListNode index=new ListNode(0);
            if(head==null) return null;
        index=head;
        while(index.next!=null){
           if(index.next.val==index.val){
               index.next=index.next.next;
         }else
               index=index.next;
        }
            return head;
    }
}

測試數據

public static void main(String[] args) {
    Solution r = new Solution ();
    ListNode L = new ListNode(1);
    L.next = new ListNode(1);
    L.next.next = new ListNode(1);
    L.next.next.next = new ListNode(2);
    L.next.next.next.next = new ListNode(3);
    L.next.next.next.next.next = new ListNode(4);
    L.next.next.next.next.next.next = new ListNode(5);
    L.next.next.next.next.next.next.next = new ListNode(6);
    //print original string
    ListNode temp = new ListNode(0);
    temp = L;
    while (temp != null) {
        System.out.print(temp.val + " ");
        temp = temp.next;
    }
    System.out.println("\n");
    L = r.deleteDuplicates(L);

    while (L != null) {
        System.out.print(L.val + " ");
        L = L.next;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章