LeetCode----- 83.Remove Duplicates from Sorted List

来源:互联网 发布:http load windows 64 编辑:程序博客网 时间:2024/06/15 10:48

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.

给定已排序好的链表,删除链表中所有的重复项,使得每个元素只显示一次。

解题思路:用两个指针pre,point分别指向链表的前一个结点和下一个结点,当这2个结点中的数据不相等时,两个指针后移;当2个结点的数据相等时,前一个结点的next指向后一个结点的next,从而删除了相等的结点。

public class RemoveDuplicatesfromSortedList {    public static ListNode deleteDuplicates(ListNode head) {    if(head == null || head.next == null) {    return head;    }    ListNode pre = head;    ListNode point = head.next;    while(point != null) {    if(pre.val == point.val) {    pre.next = point.next;    }else {    pre = pre.next;    }    point = point.next;    }        return head;    }public static void main(String[] args) {ListNode l10 = new ListNode(1);ListNode l11 = new ListNode(1);ListNode l12 = new ListNode(2);ListNode l13 = new ListNode(3);ListNode l14 = new ListNode(3);l10.next = l11;l11.next = l12;l12.next = l13;l13.next = l14;l14.next = null;ListNode node = deleteDuplicates(l10);while(node != null) {if(node.next == null) {System.out.println(node.val);}else{System.out.print(node.val +"->");}node = node.next;}}}