C++版本
#include<iostream>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
};
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (m == 1) return reverseL(head, n);
head->next = reverseBetween(head->next, m - 1, n - 1);
return head;
}
ListNode* behind = NULL;
ListNode* reverseL(ListNode* head, int L)
{
if (L == 1) {
behind = head->next;
return head;
}
ListNode* newHead = reverseL(head->next, L - 1);
head->next->next = head;
head->next = behind;
return newHead;
}
};
ListNode *InputList()
{
int n, temp;
ListNode *pHead = new ListNode();
ListNode *cur = pHead;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> temp;
if (i == 1) {
cur->val = temp;
cur->next = NULL;
} else {
ListNode *newNode = new ListNode();
newNode->val = temp;
newNode->next = NULL;
cur->next = newNode;
cur = newNode;
}
}
return pHead;
}
ListNode *ReverseList(ListNode *head)
{
if (head == nullptr || head->next == nullptr) return head;
ListNode *newHead = ReverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
void PrintList(ListNode *head)
{
while (head) {
cout << head->val;
if (head->next) cout << " -> ";
head = head->next;
} cout << endl;
}
int main() {
ListNode *head = InputList();
cout << "构造链表如下:" << endl;
PrintList(head);
head = ReverseList(head);
cout << "翻转链表后" << endl;
PrintList(head);
Solution s;
head = s.reverseBetween(head,1,2);
cout << "掐头去尾链表反转后" << endl;
PrintList(head);
head = s.reverseL(head,2);
cout << "前2个链表反转后" << endl;
PrintList(head);
return 0;
}
C版本
#include <stdio.h>
#include <stdlib.h>
#define N 5
typedef struct node {
int data;
struct node *next;
} NODE;
NODE *ReverseList(NODE *h) {
if(h == NULL || h->next == NULL) return h;
NODE *newNode = ReverseList(h->next);
h->next->next = h;
h->next = NULL;
return newNode;
}
NODE *creatlistnew(int a[]) {
NODE *pHead = (NODE *) malloc(sizeof(NODE));;
NODE *p = pHead;
for (int i = 0; i < N; i++) {
if (i == 0) {
p->data = a[i];
p->next = NULL;
}
else{
NODE *newNode = (NODE *) malloc(sizeof(NODE));
newNode->data = a[i];
newNode->next = NULL;
p->next = newNode;
p = newNode;
}
}
return pHead;
}
NODE *creatlist(int a[]) {
NODE *h, *p, *q;
int i;
h = NULL;
for (i = 0; i < N; i++) {
q = (NODE *) malloc(sizeof(NODE));
q->data = a[i];
q->next = NULL;
if (h == NULL)
h = p = q;
else{
p->next = q;
p = q;
}
}
return h;
}
void outlist(NODE *h){
NODE *p = h;
if(p == NULL)
printf("NULL\n");
else{
printf("Head");
do{
printf("->%d",p->data);
p = p->next;
} while (p!=NULL);
printf("->End\n");
}
}
int main() {
NODE *head;
int a[N] = {2,4,6,8,10};
head = creatlistnew(a);
printf("原始链表\n");
outlist(head);
head = fun(head);
printf("反转链表\n");
outlist(head);
return 0;
}
反转链表
算法备忘录~翻转单链表(ACM模式)