Last active
March 16, 2019 02:50
-
-
Save chenzhg33/9d9929ee710d30952b33d6c3ecf42d88 to your computer and use it in GitHub Desktop.
链表翻转
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdio.h> | |
#include <string> | |
#include <map> | |
#include <algorithm> | |
using namespace std; | |
struct Node { | |
Node() : value(0), next(NULL) {} | |
int value; | |
Node *next; | |
}; | |
typedef Node* NodePtr; | |
void printList(Node* head) { | |
Node* cur = head; | |
while (cur != NULL) { | |
cout << cur->value << endl; | |
cur = cur->next; | |
} | |
} | |
Node* reverse(Node* head, int n) { | |
if (head == NULL) { | |
return NULL; | |
} | |
Node* pre = NULL; | |
Node* cur = head; | |
int k = n; | |
while (cur != NULL && k-- > 0) { | |
Node* tmp = cur->next; | |
cur->next = pre; | |
pre = cur; | |
cur = tmp; | |
} | |
head->next = reverse(cur, n); | |
return pre; | |
} | |
int main() { | |
Node* head = new Node(); | |
head->value = 1; | |
Node* cur = head; | |
for (int i = 2; i < 9; i++) { | |
cur->next = new Node(); | |
cur->next->value = i; | |
cur = cur->next; | |
} | |
//printList(head); | |
Node* newHead = reverse(head, 4); | |
printList(newHead); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment