您的位置:首页 > 其它

LeetCode083 Remove Duplicates from Sorted List

2017-04-20 22:28 267 查看
详细见:leetcode.com/problems/remove-duplicates-from-sorted-list

Java Solution:
github

package leetcode;

import tools.ListNode辅助.*;
public class P083_RemoveDuplicatesFromSortedList {
public static void main(String[] args) {
ListNode head = tools.ListNode辅助.A_一维生成器(new int[] {});
ListNode ans = new Solution().deleteDuplicates(head);
tools.ListNode辅助.B_打印链表(ans);
}
/*
* 	1 ms
* 	17.15%
*/
static class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null)	return head;
ListNode cur = head.next, pre = head;
while (cur != null) {
if (cur.val == pre.val) {
cur = cur.next;
pre.next = cur;
} else {
pre = cur;
cur = cur.next;
}
}
return head;
}
}
}


C Solution:
github

/*
url: leetcode.com/problems/remove-duplicates-from-sorted-list
AC 6ms 9.62%
*/

#include <stdio.h>
#include <stdlib.h>

typedef struct ListNode * pln;
typedef struct ListNode sln;

struct ListNode {
int val;
struct ListNode *next;
};

pln deleteDuplicates(pln h) {
pln p = NULL, n = h;
while (n != NULL) {
if (p == NULL) {
p = n;
} else {
if (p->val != n->val) {
p->next = n;
p = n;
}
}
n = n->next;
}
if (p != NULL) p->next = NULL;
return h;
}

int main() {

}


Python Solution:
github

#coding=utf-8

'''
url: leetcode.com/problems/remove-duplicates-from-sorted-list
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月20日
@details: Solution: 78ms 25.05%
'''

class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self, *args, **kwargs):
return str(self.val)

def construct(l):
ln = len(l)
ls = [None] * ln
for i in range(ln-1, -1, -1):
ls[i] = ListNode(l[i])
if i != ln-1:
ls[i].next = ls[i+1]
return None if ln == 0 else ls[0]

def print_list_node(l):
print("==================")
while l != None:
print(l.val)
l = l.next
print("==================")

class Solution(object):
def deleteDuplicates(self, h):
"""
:type h: ListNode
:rtype: ListNode
"""
t, p = h, None
while t != None:
if p == None:
p = t
elif p.val != t.val:
p.next = t
p = t
t = t.next
if p != None and p.next != None:
p.next = None
return h

if __name__ == "__main__":
#test case:
s = [
[1, 2, 2, 3],
[1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6],
[2, 2, 3, 3, 4, 5, 5, 6, 6, 6, 7],
[1, 2, 2, 2, 2],
[2, 2, 3, 3, 4, 5, 5],
[2, 2, 3, 3, 4, 4, 5, 5],
[]
]
for t in s:
h = construct(t)
print_list_node(Solution().deleteDuplicates(h))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode