欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢
Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
这个题目在函数里单独弄了ListNode作为新的head,这样的话在循环里面可以统一处理而不用把开头的特殊情况拿出来
//方法一:测试Accepted class Solution { public: ListNode *deleteDuplicates(ListNode *head) { bool signal = false; ListNode tempHead(0); if(!head) { return head; } ListNode *first = head, *second = head -> next, *pre = &tempHead; tempHead.next = head; while(second) { while(second && first -> val == second -> val) { signal = true; first = second; second = second -> next; } if(!signal) { pre = first; first = second; second = second -> next; } else { pre -> next = second; first = second; if(second) second = second -> next; } signal = false; } return tempHead.next; } };
#include<iostream> using namespace std; #define N 7 struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *deleteDuplicates(ListNode *head) { bool signal = false; ListNode tempHead(0); if(!head) { return head; } ListNode *first = head, *second = head -> next, *pre = &tempHead; tempHead.next = head; while(second) { while(second && first -> val == second -> val) { signal = true; first = second; second = second -> next; } if(!signal) { pre = first; first = second; second = second -> next; } else { pre -> next = second; first = second; if(second) second = second -> next; } signal = false; } return tempHead.next; } }; ListNode *creatlist(){ ListNode *list; list = NULL; ListNode *p; for(int i=0; i<N; i++) { int a; cin>>a; p = (ListNode*)malloc(sizeof(ListNode)); p->val = a; p->next=list; //指定后继指针 list = p; //head指针指定到新插入的结点上 } return list; } int main() { ListNode *list = creatlist(); Solution lin; ListNode *outlist=lin.deleteDuplicates(list); for(int i=0; i<N; i++) { cout<<outlist->val; outlist = outlist->next; } }
时间: 2024-10-09 06:26:01