LeetCode-Remove Duplicates from Sorted List

来源:互联网 发布:c语言putchar 32 编辑:程序博客网 时间:2024/06/07 00:56
作者:disappearedgod
文章出处:http://blog.csdn.net/disappearedgod/article/details/24017575
时间:2014-4-18

题目

Remove Duplicates from Sorted List

 Total Accepted: 13376 Total Submissions: 39241My Submissions

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.

 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 ret = new ListNode(Integer.MIN_VALUE);        ListNode p = ret;        int record = Integer.MIN_VALUE;        while(head!=null){            if(record<head.val){                record = head.val;                p.next = new ListNode(record);                p = p.next;            }            head= head.next;        }        return ret.next;    }}

上述方法太讨巧,不是链表操作,上一个链表操作
public ListNode deleteDuplicates(ListNode head) {        return delete(head);    }    public ListNode delete(ListNode head) {        if(head==null||head.next==null)            return head;        int record = Integer.MIN_VALUE;        ListNode dummy = new ListNode(Integer.MIN_VALUE);        dummy.next = head;        ListNode p = dummy;        while(p.next!=null){            ListNode nextnode = p.next;            if(p.val == nextnode.val){                    p.next = nextnode.next;            }            else                p = p.next;        }        return dummy.next;    }



返回

LeetCode Solution(持续更新,java>c++)

0 0
原创粉丝点击