Reverse a one-way linked list, that is, 1-> 2-> 3-> 4->... -> n-1-> A chain table like n is reversed to n-> n-1->... 3-> 2-> 1. You can delete the nodes in the linked list in sequence, so that the next pointer of the linked list refers to the previous element, and the link with the subsequent element is cut off. In this way, the complexity of the algorithm is O (N). You only need N traversal times to reverse the linked list. The Code is as follows:
[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, 4, 5, 6, 7, 8, 9, 10 };
LinkList head = (LinkList) malloc (sizeof (Node ));
List (arr, head, 10 );
Traverse (head );
Reverse (head );
}