題目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 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) {
ListNode* cur = head;
while(cur && cur->next){
if(cur->val == cur->next->val){
cur->next = cur->next->next;
} else {
cur = cur->next;
}
}
return 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 cur = head;
while(cur!=null && cur.next!=null){
if(cur.val == cur.next.val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
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
"""
cur = head
while cur and cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
解法2:遞歸:
遞歸基:
如果只有一個結點或者沒有結點,則返回
判斷當前結點和它的下一個結點的值,如果相等,則捨棄當前結點,繼續遞歸它的下一個結點
如果不等,繼續遞歸它的下一個結點,但是要通過指針操作將當前結點與下一個結點接上,並返回當前結點
/**
* 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(!head || !(head->next)) return head;
if(head->val == head->next->val){
return deleteDuplicates(head->next);
} else {
head->next = deleteDuplicates(head->next);
}
return 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) {
if(head == null || head.next == null){
return head;
}
if(head.val == head.next.val){
return deleteDuplicates(head.next);
}else{
head.next = deleteDuplicates(head.next);
}
return head;
}
}
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 not head or not head.next:
return head
if head.val == head.next.val:
return self.deleteDuplicates(head.next)
else:
head.next = self.deleteDuplicates(head.next)
return head