/*
 * @lc app=leetcode.cn id=83 lang=c
 *
 * [83] 删除排序链表中的重复元素
 *
 * https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/description/
 *
 * algorithms
 * Easy (44.24%)
 * Total Accepted:    18.4K
 * Total Submissions: 41.5K
 * Testcase Example:  '[1,1,2]'
 *
 * 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
 * 
 * 示例 1:
 * 
 * 输入: 1->1->2
 * 输出: 1->2
 * 
 * 
 * 示例 2:
 * 
 * 输入: 1->1->2->3->3
 * 输出: 1->2->3
 * 
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* deleteDuplicates(struct ListNode* head) {
    struct ListNode *p,*q;

    if(head==NULL){
        return NULL;
    }else if(head!=NULL&&head->next==NULL){
        return head;
    }else
    {
       p = head;
       q = head->next;
    }

    while(p!=NULL){
        while(q!=NULL){
            if(q->val==p->val){
                p->next = q->next;
                q->next = NULL;
                q = p->next;
                continue;
            }
            q=q->next;
        }
        p = p->next;
        if(p!=NULL&&p->next!=NULL){
            q = p->next;
        }else
        {
            q = p;
        }
    }
    return head;
}

自己写的,思路简单,但是写的有点复杂了。

主要思路就是 设置两个结点指针,然后一个节点从头开始,另一个节点在它之后依次移动,找到相等的值就删去这个节点。

有些地方复杂了就是多了点处理,首先开始判断传进来的链表,空的话返回空,只有头的话就返回头。

然后在循环过程中发现,比如 1 1 这种情况,所以在循环最后加了判断,如果移动到末尾的情况。

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

python:

#
# @lc app=leetcode.cn id=83 lang=python3
#
# [83] 删除排序链表中的重复元素
#
# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/description/
#
# algorithms
# Easy (44.24%)
# Total Accepted:    18.4K
# Total Submissions: 41.5K
# Testcase Example:  '[1,1,2]'
#
# 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
# 
# 示例 1:
# 
# 输入: 1->1->2
# 输出: 1->2
# 
# 
# 示例 2:
# 
# 输入: 1->1->2->3->3
# 输出: 1->2->3
# 
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head:
            return head
        p = head
        q = head.next
        while q!=None:
            if q.val!=p.val:
                p = q
                q = q.next
            else:
                p.next = q.next
                q = q.next
        return head