首页 > 学院 > 开发设计 > 正文

LeetCode-83. Remove Duplicates from Sorted List

2019-11-06 08:06:29
字体:
来源:转载
供稿:网友

问题: https://leetcode.com/PRoblems/remove-duplicates-from-sorted-list/?tab=Description 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. 给定一个有序链表,删除所有重复元素,使得每个元素只出现一次。 例如, 给定1->1->2,返回1->2。 给定1->1->2->3->3,返回1->2->3。 分析: 循环检测,如果两个元素值相同,就删掉一个。 参考C++代码:

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* deleteDuplicates(ListNode* head) { ListNode* h=new ListNode(0); h->next=head; if(head==NULL) return NULL; for(ListNode* p=h;p->next!=NULL;p=p->next){ while(p->next->next!=NULL && p->next->val==p->next->next->val ) p->next=p->next->next; } return h->next; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表