Leetcode:83. Remove Duplicates from Sorted List(JAVA)

来源:互联网 发布:网络暴力赚钱项目 编辑:程序博客网 时间:2024/06/14 20:59

【问题描述】

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.

【思路】

维护两个指针,temp,tempnext,如果temp.val == tempnext.val,temp指向tempnext的后一位,同时tempnext后移,否则temp指针后移。

public class Solution {    public ListNode deleteDuplicates(ListNode head) {        if(head == null)            return head;                ListNode temp = head, tempnext = head.next;        while(tempnext != null){            if(temp.val == tempnext.val ){                temp.next = tempnext.next;                tempnext = tempnext.next;            }else{                temp = temp.next;            }        }                return head;    }}


0 0
原创粉丝点击