Remove Duplicates from Sorted List 题解
题目来源:https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
Description
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Solution
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head -> next == NULL)
return head;
ListNode *preNode = head, *curNode = head -> next;
while (curNode) {
if (preNode -> val == curNode -> val) {
preNode -> next = curNode -> next;
curNode = preNode -> next;
continue;
}
if (curNode == NULL)
break;
preNode = curNode;
curNode = curNode -> next;
}
return head;
}
};
解题描述
这道题题意是删除已经排好序的链表中的重复元素,这里我用到的方法是检查相邻节点元素是否相同然后将指针进行重新指向的做法。
这里其实有个地方要注意的是,原来的链表不一定是通过动态内存申请得到的,比如我采用以下例程来测试函数:
int main() {
ListNode nodes[6] = {ListNode(1), ListNode(1), ListNode(1), ListNode(2), ListNode(2), ListNode(3)};
for (int i = 0; i < 5; i++) {
nodes[i].next = &nodes[i + 1];
}
ListNode *head = &nodes[0];
head = Solution().deleteDuplicates(head);
while (head) {
cout << head -> val << " ";
head = head -> next;
}
cout << endl;
return 0;
}
此时节点都是在main
函数的栈上,如果在移除节点的时候调用delete
释放节点内存就会出现非法释放内存的内存错误。所以在函数中不应该直接释放节点内存。