將一個單向鏈表反轉,也就是將1->2->3->4->...->n-1->n這樣的鏈表反轉變為n->n-1->...3->2->1,可以這樣做,順序刪除鏈表中的節點,使鏈表的next指針指向前一個元素,切斷與後面元素的聯系。這樣算法的復雜度是O(N),只需要N次遍歷就可以將鏈表反轉,代碼如下:
[cpp]
#include <stdio.h>
#include <stdlib.h>
typedef struct Node* LinkList;
struct Node{
struct Node* next;
int data;
}Node;
void list(int arr[],LinkList l,int n){
int i;
LinkList p = l, s;
for(i = 0; i < n; i++){
s = (LinkList)malloc(sizeof(Node));
s->data = arr[i];
p->next = s;
p = s;
}
p->next = NULL;
}
void traverse(LinkList l){
LinkList p = l->next;
while(p != NULL){
printf("%d\t", p->data);
p = p->next;
}
printf("\n");
}
void reverse(LinkList l){
LinkList p = l->next;
LinkList s = NULL, q = NULL;
while(p != NULL){
s = p->next;
p->next = q;
q = p;
p = s;
}
LinkList h = (LinkList)malloc(sizeof(Node));
h->next = q;
traverse(h);
}
int main(int argc, char * argv[]){
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
LinkList head = (LinkList)malloc(sizeof(Node));
list(arr, head, 10);
traverse(head);
reverse(head);
}