Remove Duplicates from Sorted List

来源:互联网 发布:酷狗音乐无法使用网络 编辑:程序博客网 时间:2024/04/29 16:38
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.

package leetcode;class ListNode {      int val;      ListNode next;      ListNode(int x) {          val = x;          next = null;     }}public class RemoveDuplicatesFromSortedList {public ListNode deleteDuplicates(ListNode head) {if(head == null) return null;ListNode cur = head;ListNode next = head.next;while(true){if(next == null) {cur.next = null; break;}if(cur.val == next.val) next = next.next;else {cur.next = next;cur = next;next = cur.next;}}        return head;    }}
0 0
原创粉丝点击