您的位置:首页 > 产品设计 > UI/UE

82. Remove Duplicates from Sorted List II My Submissions Question

2016-03-17 16:07 225 查看
<p style="margin-top: 0px; margin-bottom: 10px; box-sizing: border-box; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only <span style="box-sizing: border-box;">distinct</span> numbers from the original list.</p><p style="margin-top: 0px; margin-bottom: 10px; box-sizing: border-box; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">For example,<br style="box-sizing: border-box;" />Given <code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13.3333px; padding: 2px 4px; color: rgb(199, 37, 78); border-radius: 4px; background-color: rgb(249, 242, 244);">1->2->3->3->4->4->5</code>, return <code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13.3333px; padding: 2px 4px; color: rgb(199, 37, 78); border-radius: 4px; background-color: rgb(249, 242, 244);">1->2->5</code>.<br style="box-sizing: border-box;" />Given <code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13.3333px; padding: 2px 4px; color: rgb(199, 37, 78); border-radius: 4px; background-color: rgb(249, 242, 244);">1->1->1->2->3</code>, return <code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13.3333px; padding: 2px 4px; color: rgb(199, 37, 78); border-radius: 4px; background-color: rgb(249, 242, 244);">2->3</code>.</p><p style="margin-top: 0px; margin-bottom: 10px; box-sizing: border-box; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">solution:</p>
/*** 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) {if(head == NULL || head->next == NULL)return head;ListNode *pre = head;ListNode *cur = head->next;while(pre->val == cur->val){while(cur != NULL && cur->val == pre->val){cur = cur->next;}if(cur == NULL) return NULL;else{head = cur;if(cur->next == NULL) return cur;else{pre = cur;cur = cur->next;}}}while(cur->next != NULL){ListNode *p = cur->next;if(p->val == cur->val){while(p != NULL && p->val == cur->val){p = p->next;}if(p == NULL){pre->next = NULL;return head;}else{pre->next = p;cur = p;}}else{pre = pre->next;cur = cur->next;}}return head;}};
心得: 思路简单速度:快
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: