力扣83. 删除排序链表中的重复元素
1、C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head){
if(head==NULL||head->next==NULL){
return head;
}
struct ListNode* p = head;
struct ListNode* q = head->next;
while(q!=NULL){
if(p->val==q->val){
p->next = q->next;
free(q);
if(p!=NULL){
q = p->next;
}
}
else{
p = q;
q = q->next;
}
}
return head;
}
2、C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==nullptr||head->next==nullptr)return head;
ListNode* p = head;
ListNode* q = head->next;
while(q!=nullptr){
if(p->val==q->val){
p->next = q->next;
delete q;
if(p!=nullptr){
q = p->next;
}
}
else{
p = q;
q = q->next;
}
}
return head;
}
};
3、JAVA
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null)return head;
ListNode p = head;
ListNode q = head.next;
while(q!=null){
if(p.val==q.val){
p.next = q.next;
if(p!=null){
q = p.next;
}
}
else{
p = q;
q = q.next;
}
}
return head;
}
}
4、Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
p = head
q = head.next
while(q is not None):
if p.val == q.val:
p.next = q.next
if p is not None:
q = p.next
else:
p = q
q = p.next
return head