[链表翻转] 对链表进行翻转,时间复杂度为 O(n) #线性表
#include <iostream>
#include <malloc.h>
using namespace std;
typedef struct Node {
int n;
struct Node* next;
}Node, *Linklist;
void ReverseLinklist(Linklist &L) {
Linklist p = L->next, q = p->next, r = q->next;
p->next = NULL; //第一个结点指向 NULL
while(q) {
q->next = p;
p = q;
q = r;
if(r) r = r->next;
}
L->next = p;
}
void ShowLinklist(Linklist L) {
cout << L->next->n;
Linklist p = L->next->next;
while(p) {
cout << "->" << p->n;
p = p->next;
}
cout << endl;
}
int main() {
Linklist L = (Linklist)malloc(sizeof(Node)); //生成头结点
L->next = NULL;
for(int i=6; i>=1; i--) { //生成链表 1->2->3->4->5->6
Linklist p = (Linklist)malloc(sizeof(Node));
p->n = i;
p->next = L->next;
L->next = p;
}
ShowLinklist(L);
ReverseLinklist(L);
ShowLinklist(L);
return 0;
}