本文主要是介绍《leetCode》:Remove Duplicates from Sorted List,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
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.
题目大意:将所有不同的节点连接起来,即每个节点仅出现一次,去除多余的相同的节点。
思路
此题比较简单,将所有不同的节点连接起来就好。
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
struct ListNode* deleteDuplicates(struct ListNode* head) {if(head==NULL){//有效性检查 return NULL;} struct ListNode* cur=head;int val=head->val; struct ListNode* pre=head;//用来记录当前结点的值 struct ListNode* next=NULL;while(cur->next!=NULL){next=cur->next;if(val!=next->val){//将第一次出现的节点next加入到结果中 pre->next=next;//连接当前节点 pre=next;//更新最后一个节点val=next->val;}cur=next; }pre->next=NULL;return head;
}
最后AC结果如下:
这篇关于《leetCode》:Remove Duplicates from Sorted List的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!