Leetcode ☞ 83. Remove Duplicates from Sorted List

来源:互联网 发布:ios sql 编辑:程序博客网 时间:2024/06/06 19:21

83. Remove Duplicates from Sorted List

My Submissions
Total Accepted: 104147 Total Submissions: 287114 Difficulty: Easy

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.











我的AC(4ms,最快一批):

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* deleteDuplicates(struct ListNode* head) {            struct ListNode *p = head;    while(p && p->next){        if(p->val == p->next->val)            p->next = p->next->next;        else            p = p->next;    }     return head;}


注意点:

while(p && p->next)而非while(p)  ,否则p为最后一个节点的时候 取 p->next->val 会出错。最终是Runtime Error

循环里是if {巴拉巴拉} else{巴拉巴拉}










0 0