描述:给出一个链表和一个数k,比如,链表为1→2→3→4→5→6,k=2,则翻转后2→1→6→5→4→3,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→6→5,用程序实现。
#include <iostream>
using namespace std;
typedef int Type;
typedef struct LNode {
Type key;
LNode* next;
};
LNode* reverseLinkList(LNode* head) {
if (!head) {
return NULL;
}
LNode* reversedHead = NULL;
LNode* curNode = head;
LNode* prev = NULL;
while (curNode) {
LNode* next = curNode->next;
if (!next) {
reversedHead = curNode;
}
//指针反转
curNode->next = prev;
//下一状态
prev = curNode;
curNode = next;
}
return reversedHead;
}
void traverseList(LNode* head) {
if (!head) {
return;
}
while (head) {
cout << head->key << ' ';
head = head->next;
}
cout << endl;
}
void test() {
int len = 3;
LNode** nodes = new LNode*[len];
memset(nodes, NULL, sizeof(LNode*) * len);
if (len <= 0) {
return;
}
nodes[0] = new LNode();
nodes[0]->key = 1;
for (int i = 1; i < len; ++i) {
nodes[i] = new LNode();
nodes[i]->key = i + 1;
nodes[i - 1]->next = nodes[i];
}
nodes[len - 1]->next = NULL;
cout << "before reverse: ";
traverseList(nodes[0]);
LNode* reHead = reverseLinkList(nodes[0]);
cout << "after reverse: ";
traverseList(reHead);
}
int main() {
test();
return 0;
}