Single-chain table reversal (C code)

Source: Internet
Author: User

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 );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.