删除一个有序单链表的重复节点
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
思路:两个指针,一前一后,前面指针的值与后面指针的值相等就往前,直到不同,后指针的下一个节点指向前指针,然后继续。
注意一下边界:
- 头指针为空
- 链表只有一个节点
尾部需要处理
class Solution {public: ListNode *deleteDuplicates(ListNode *head) { if (!head || !head->next) { return head; } ListNode* forward = head->next; ListNode* backward = head; while (forward-> next!= NULL) { if (forward->val == backward->val) { forward = forward->next; } else { backward->next = forward; backward = forward; forward = forward->next; } } if (backward->val == forward->val) { backward->next = NULL; } else { backward->next = forward; } return head; }};
来源:https://www.cnblogs.com/flyjameschen/p/4341304.html