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
.
思路:
1. 前提是整个链表是有序的
2. 循环遍历整个链表,对于相同的元素值要注意将前指针指向后续的下一个结点
直接上Code:
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
struct ListNode* deleteDuplicates(struct ListNode* head) {if (head == NULL)return NULL;struct ListNode* p = NULL, *q = NULL;p = head;q = p->next;while(q) {struct ListNode *tmp = q->next;if (!(p->val ^ q->val)){//same elementp->next = tmp;free(q); q = tmp;}else {p = q;q = q->next;}}return head;
}
算法时间复杂度O(n)。