Description:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 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* curr = head; while(curr && curr->next){ if (curr->val == curr->next->val){ ListNode *temp = curr->next; curr->next = temp->next; delete temp; } else curr = curr->next; } return head; } };
运行时间:12ms
运行内存:9.1M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于