您的位置:首页 > Web前端 > Node.js

25-Reverse Nodes in k-Group

2017-11-02 22:51 447 查看
难度:hard

类别:linked list

1.题目描述

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

2.算法分析

(1)对k不满足情况以及head和head->next为null的情况进行特殊处理

(2)计算list的长度

(3)对于每k个数,将它们压如栈中,然后pop出来并添加到新的链表中

(4)将最后的不足k个数添加到新的链表的尾部

3.代码实现

#include <iostream>
#include <stack>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) :val(x), next(NULL) {}
};
//  每k个数就进行反转,如果剩下的不是k的倍数,就按照原来的顺序
ListNode* reverseKGroup(ListNode* head, int k) {
if (head == NULL || head->next == NULL || k == 0 || k == 1) return head;
stack<int> mystack;
int count = 0;
ListNode* temp = head;
while (temp != NULL) {
count++;
temp = temp->next;
}
temp = head;
int n = 1;
ListNode* result = NULL;
ListNode* ans = NULL;
if (k > count) return head;
while (n*k <= count) {
for (int i = 0; i < k; i++) {
mystack.push(temp->val);
temp = temp->next;
}
if (n == 1) {
result = new ListNode(mystack.top());
mystack.pop();
ans = result;
}
while (!mystack.empty()) {
result->next = new ListNode(mystack.top());
mystack.pop();
result = result->next;
}
n++;
}
if (temp != NULL) {
result->next = temp;
}
return ans;
}
void printList(ListNode* head) {
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main() {
int n, num, k;
cin >> n >> k;
ListNode* head = NULL;
ListNode* temp = NULL;
for (int i = 0; i < n; ++i) {
cin >> num;
if (i == 0) {
head = new ListNode(num);
temp = head;
}
else {
head->next = new ListNode(num);
head = head->next;
}
}
printList(temp);
temp = reverseKGroup(temp, k);
printList(temp);
system("pause");
return 0;
}


4.小结

本题并不难,利用栈的FILO性质即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 25 reverse list