[LeetCode] Remove Duplicates from Sorted List

来源:互联网 发布:阿里云售后电话号码 编辑:程序博客网 时间:2024/06/10 19:29
Problem : Given a sorted linked list, delete all duplicates such that each element appear onlyonce.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

1.C++版

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *deleteDuplicates(ListNode *head) {        if(NULL == head){            return NULL;        }                ListNode *p = head;        while(NULL != p->next){            if(p->val == p->next->val){                p->next = p->next->next;            }else{                p = p->next;            }        }                return head;    }};

2.Java版

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

3.Python版

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @param head, a ListNode    # @return a ListNode    def deleteDuplicates(self, head):        if None == head:            return None                    p = head        while None != p.next:            if p.val == p.next.val:                p.next = p.next.next            else:                p = p.next                        return head 


0 0
原创粉丝点击