[Leetcode]-Remove Duplicates from Sorted List

来源:互联网 发布:女仆装淘宝网 编辑:程序博客网 时间:2024/06/05 18:42

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

题目:输入一个排序好的链表,其中可能有元素是重复的,找出重复数据元素,栓出多余的重复元素,只保留一个。
思路:链表节点栓出要比数组简单多了,可以在链表本身中操作。
判断当前节点的下一个节点的值是否于当前节点的值相同:
A:如果相同,删除下一个节点。
B:继续判断下一个节点的值是否于当前节点的值相同,如果不同这将P指针指向下一个节点,如果相同,指针P保持不动,直到删除所有的与当前节点值相同的下一节点。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; *///delete the next node of Pvoid DeleteNextNode(struct ListNode* L,struct ListNode* P){    struct ListNode* tem =NULL;    if(P->next->next != NULL)    {        tem = P->next;        P->next = tem->next;        free(tem);    }    else       P->next = NULL; }struct ListNode* deleteDuplicates(struct ListNode* head) {    if(head == NULL)        return NULL;    struct ListNode* P = head;    while(P->next != NULL)    {        if(P->val == P->next->val)            DeleteNextNode(head,P);        if(P->next != NULL && P->val != P->next->val)            P = P->next;        else            continue;    }    return head;}
1 0
原创粉丝点击