BM15. 删除有序链表中重复的元素-I
描述
示例1
输入:
{1,1,2}
输出:
{1,2}
示例2
输入:
{}
输出:
{}
C++ 解法, 执行用时: 0ms, 内存消耗: 8552KB, 提交时间: 2015-03-17
/** * 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 *p; ListNode *q; p = head; while (p!=NULL && p->next!=NULL) { if (p->val == p->next->val) { ListNode *temp; temp = p->next; p->next = temp->next; free(temp); } else { p = p->next; } } return head; } };
C++ 解法, 执行用时: 0ms, 内存消耗: 8684KB, 提交时间: 2015-03-17
/** * 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 *cur=head,*nxt; int val; while(cur){ val=cur->val; nxt=cur->next; while(nxt&&nxt->val==val) nxt=nxt->next; cur->next=nxt; cur=nxt; } return head; } };
C++ 解法, 执行用时: 0ms, 内存消耗: 8684KB, 提交时间: 2015-03-17
/** * 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* root = head; while(head != NULL) { /*下一节点存在,且当前节点和下一节点的值重复*/ while(head->next != NULL && head->val == head->next->val) { head->next = head->next->next; } head = head->next; } return root; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 332KB, 提交时间: 2021-05-12
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @return ListNode类 */ ListNode* deleteDuplicates(ListNode* head) { // write code here if(head == NULL) return head; ListNode* temp = head; while(temp->next!=NULL){ if(temp->val == temp->next->val){ temp->next = temp->next->next; } else{ temp = temp->next; } } return head; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 332KB, 提交时间: 2020-11-23
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @return ListNode类 */ ListNode* deleteDuplicates(ListNode* head) { // write code here if(head==NULL) { return NULL; } for(ListNode* i=head;i!=NULL;i=i->next) { for(ListNode* j=i->next;j!=NULL;j=j->next) { if(i->val==j->val) { i->next=j->next; } } } return head; } };