本文共 1302 字,大约阅读时间需要 4 分钟。
传送门: 购买视频请输入优惠码 AdVHxHT 可优惠10元
题目描述:
有一个单链表,请设计一个算法,使得每K个节点之间逆序,如果最后不够K个节点一组,则不调整最后几个节点。例如链表1->2->3->4->5->6->7->8->null,K=3这个例子。调整后为,3->2->1->6->5->4->7->8->null。因为K==3,所以每三个节点之间逆序,但其中的7,8不调整,因为只有两个节点不够一组。
给定一个单链表的头指针head,同时给定K值,返回逆序后的链表的头指针。
AC 代码
class KInverse {public: ListNode* inverse(ListNode* head, int k) { stacks; ListNode * newHead = NULL,*last=NULL; while (head) { ListNode *tmp = head->next; head->next = NULL; s.push(head); head = tmp; if(s.size()==k){ while (!s.empty()) { if(newHead==NULL){ newHead = s.top(); last = s.top(); }else{ last->next = s.top(); last = s.top(); } s.pop(); } } } ListNode * remain=NULL; while (!s.empty()) { if(remain==NULL){ remain = s.top(); }else{ (s.top())->next = remain; remain = s.top(); } s.pop(); } if(newHead==NULL) return remain; else{ last->next = remain; return newHead; } }};
转载地址:http://ehhji.baihongyu.com/