Programming Algorithm-reverse code of linked list (c)

Source: Internet
Author: User
Reverse code of linked list (c)


Address: http://blog.csdn.net/caroline_wendy


Reverse Sequence of linked listAs the basis for linked list operationsRequiredBe proficient in handwriting.

Mainly includeThree parts, A pointer records the subsequent nodes, a pointer records the previous node, pointing the current node to the previous node, moving to the next node, and moving the front and back pointers in turn.

Non-recursive reverse list AlgorithmCore codeOnly 10 rows.


Code:

/** Main. CPP ** created on: 2014.9.12 * Author: Spike * // * eclipse CDT, GCC 4.8.1 */# include <stdio. h> # include <stdlib. h> struct listnode {int data; listnode * Next;}; void printlist (listnode * head); listnode * reverselist (listnode * head); int main () {listnode * head = new listnode (); listnode * node1 = new listnode (); listnode * node2 = new listnode (); listnode * node3 = new listnode (); listnode * node4 = new lis Tnode (); head-> DATA = 0; head-> next = node1; node1-> DATA = 1; node1-> next = node2; node2-> DATA = 2; node2-> next = node3; node3-> DATA = 3; node3-> next = node4; node4-> DATA = 4; node4-> next = NULL; printlist (head ); listnode * Re = reverselist (head); printlist (re); Return 0;} listnode * reverselist (listnode * head) {If (Head = NULL | head-> next = NULL) {return head; /* If the linked list is empty or there is only one element, the system directly returns */} listnode * Prev = NULL; lis Tnode * Next = NULL; while (Head! = NULL) {next = head-> next; head-> next = Prev; Prev = head; head = next;} return Prev;} void printlist (listnode * head) {While (Head! = NULL) {printf ("% d", head-> data); Head = head-> next;} printf ("\ n ");}

Output:

0 1 2 3 4 4 3 2 1 0 







Programming Algorithm-reverse code of linked list (c)

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.