83 Remove Duplicates from Sorted List
循环过一遍, 如果和上一个元素相同,那么忽略它,不同,则添加到新的链表里面。
可以多使用一个循环减少多余的空间开销。
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
new_head = ListNode(head.val)
cur = new_head
p = head.next
while p:
if p.val != cur.val:
cur.next = ListNode(p.val)
cur = cur.next
p = p.next
return new_head
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode ret = new ListNode(-1);
ret.next = head;
while(head != null){
while(head.next != null && head.next.val == head.val){
head.next = head.next.next;
}
head = head.next;
}
return ret.next;
}
}