leetcode remove-duplicates-from-sorted-list有序链表去重

For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

/**
 * 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||head.next==null) return head;
        ListNode cur = head.next;
        ListNode pre = head;
        head.next = null;
        while(cur!=null){
            if(pre.val==cur.val){
                cur = cur.next;
            }
            else{
                pre.next = cur;
                pre = cur;
                cur = cur.next;
                pre.next = null;
            }
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/victor_socute/article/details/89299682