【Leetcode】 83. Remove Duplicates from Sorted List 【两个指针】

来源:互联网 发布:sql server 2005 端口 编辑:程序博客网 时间:2024/05/16 01: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.

这道题的要求是在有序链表中删除有重复数字的节点,使其只出现1次。

思路就是找到重复元素,删除即可。循环检测,如果两个连续节点的数字一样,删除一个重复的元素。

时间复杂度:O(n)

空间复杂度:O(1)


代码:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode deleteDuplicates(ListNode head) {        if(head == null || head.next == null)  return head;        ListNode begin = head;        ListNode curr = head.next;        ListNode last = head;        while( curr != null ){            if(last.val == curr.val){                last.next = curr.next;                curr.next = null;                curr = last.next;            }            else{                last = curr;                curr = curr.next;            }        }        return begin;    }}

注意:while循环的写法


另一种做法:(并没有卵用,除了能记录一下重复的次数,再删掉)

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode deleteDuplicates(ListNode head) {        if(head == null || head.next == null) return head;        int step = 0 ;        ListNode begin = head ;        ListNode curr = head.next;        ListNode last = head;                while(curr != null){            if(curr.val == last.val){                step ++;                curr = curr.next;                if(curr == null){                    if(step != 0){                        last.next = curr;                    }                }            }            else{                if(step == 0){                    last = curr;                    curr = curr.next;                }                else if(step != 0){                    last.next = curr;                    last = curr;                    curr = curr.next;                    step = 0 ;                }            }        }        return begin;    }}


0 0
原创粉丝点击