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 P
void 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;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
[Leetcode]-Remove Duplicates from Sorted List
原文:http://blog.csdn.net/xiabodan/article/details/46771915