LeetCode刷题之Remove Duplicates from Sorted List

Problem

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.
My Solution
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode p, q;
        if (head == null || head.next == null) {
            return head;
        } else {
            p = head;
            q = head.next;
        }
        while (q != null) {
            if (p.val != q.val) {
                p = p.next;
                p.val = q.val;
            }
            q = q.next;
        }
        p.next = null;
        return head;
    }
}
Great Solution
public ListNode deleteDuplicates(ListNode head) {
    ListNode current = head;
    while (current != null && current.next != null) {
        if (current.next.val == current.val) {
            current.next = current.next.next;
        } else {
            current = current.next;
        }
    }
    return head;
}
    原文作者:Gandalf0
    原文地址: https://www.jianshu.com/p/d83e7b743cfd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞