大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Input: head = [1,1,2]
Output: [1,2]
Input: head = [1,1,2,3,3]
Output: [1,2,3]
[0, 300]
.-100 <= Node.val <= 100
sorted
in ascending order.首先先簡單的翻譯一下題目
給一個排序過後的linked list,要把其中重複的節點刪除。
作法大致上是這樣
once
用來存有出現一次的值,再抓到每個節點的值的時候就進來判斷有沒有遇到過,沒有就存入。next
指向現在這個節點的next
,就完成啦~# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
once = []
start = head
previous = None
while start != None:
print(start.val)
if start.val not in once:
once.append(start.val)
previous = start
else:
previous.next = start.next
start = start.next
return head
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head){
int num = -101;
struct ListNode* start = head;
struct ListNode* previous = 0;
while (start != 0){
// printf("%d\n", start->val);
// printf("%d\n", start->next);
if (start == head){
num = start->val;
previous = start;
} else {
if (start->val > num){
num = start->val;
previous = start;
} else if (start->val == num){
previous->next = start->next;
}
}
start = start->next;
}
return head;
}
Python
C
大家明天見