本文共 1864 字,大约阅读时间需要 6 分钟。
问题截图:
错误代码及测试用例:
/** - Definition for singly-linked list. - struct ListNode { - int val; - ListNode *next; - ListNode(int x) : val(x), next(NULL) {} - }; */class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode *res=new ListNode; ListNode *p=head,*r=head;; ListNode *q=res; stacks; while(p!=NULL){ int n=k; while(n){ if(p==NULL){ while(r){ q->next=r; r=r->next; q=q->next; } return res->next; } s.push(p); p=p->next; n--; } while(!s.empty()){ q->next=s.top(); s.pop(); q=q->next; } if(p==NULL) return res->next; r=p; } return res->next; }};出错测试用例:[1,2]2经过多次测试发现,只要是链表长度能被K整除就出错,也就是入栈循环结束后p为null
寻错过程:
解决方法:在结点出栈的时候使出栈结点指向NULL
解决后成功运行的代码(改动部分):
for(int i=0;inext=s.top(); // if(i==1) return res; s.pop(); q=q->next; q->next=NULL; // if(i==1) return q; }
转载地址:http://jiemb.baihongyu.com/