简单AC
删除有序链表中重复出现的元素
http://www.nowcoder.com/questionTerminal/71cef9f8b5564579bf7ed93fbe0b2024
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
ListNode* newhead = new ListNode(0);
newhead->next = head;
ListNode* pre = newhead;
ListNode* cur = head;
int count = 0;
while(cur != NULL && cur->next != NULL){
if(cur->val == cur->next->val){
cur->next = cur->next->next;
count++;
}
else{
if(count > 0){
pre->next = cur->next;//让链表跳过重复的节点
count = 0;
}
else{
pre = cur;
}
cur = cur->next;
}
}
//判断尾节点是否需要删除
if(count > 0)
pre->next = cur->next;
return newhead->next;
}
};
联想公司福利 1489人发布