删除已排序单链表中重复的元素

来源:互联网 发布:樱井知香ed2k file 编辑:程序博客网 时间:2024/05/01 18:12
/*
   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.


   Subscribe to see which companies asked this question
 */


对于已经排好序的link-list,这样的删除还是很简单。
先记录当前的值为head->val,然后往后逐一判断,在nextnode为空时结束。
如果nextnode->val跟当前值相等,则prenode->next = nextnode->next即删除掉,然后nextnode=prenode->next。

如果nextnode->val跟当前值不等(一定是大于),则重置当前值为nextnode->val,并且prenode=nextnode, nextnode=nextnode->next。


struct ListNode {
int val;
struct ListNode *next;
};


struct ListNode* deleteDuplicates(struct ListNode* head) { 
   if (head == NULL ||  head->next == NULL) { 
       return head; 
   }   
   struct ListNode* prenode = head;
   struct ListNode* nextnode = head->next;
   int curval = head->val;
   while(nextnode) {
if (nextnode->val == curval) { 
   prenode->next = nextnode->next;
nextnode = prenode->next;
}
else {
curval = nextnode->val;
prenode = nextnode;
nextnode = nextnode->next;
}
   }
   return head;

0 0
原创粉丝点击