本文共 1213 字,大约阅读时间需要 4 分钟。
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
/** * 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--; } for(int i=0;i next=s.top(); // if(i==1) return res; s.pop(); q=q->next; q->next=NULL; // if(i==1) return q; } if(p==NULL) return res->next; r=p; } return res->next; }};
通过时间:
转载地址:http://ciemb.baihongyu.com/