Inverse traversal and inversion algorithm for linked list operation rules

Source: Internet
Author: User

first, create the linked list:

The premise of all the algorithms that operate on a linked list is that we first create a linked list, and we can choose to forward and reverse-build the chain:

(a), forward to build the chain:

First, we have to customize the node type:

typedefstruct Node{    int data;//数据域    struct Node * pNext;//指针域}NODE,*PNODE;

To assign values to a linked list data field by using an array:

int main (void){    PNODE pHead;//头指针,接收创建链表时返回的头结点地址    int a[8] = {12,37,49,65,24,99,8,11};    //PNODE = ForwardCreate_Link (a,8);//正向建链    PNODE = ReverseCreate_Link (a,8);//逆向建链    Print_Link(pHead);//遍历链表}

The basic idea of a forward chain is to create a head node and then insert a node at the end of the list, called the tail plug. The code is as follows:

/ * Positive Build chain * /Pnode Forwardcreate_link (intAintLen//Return value type is struct Node * type{Pnode phead, ptail; Phead =NULL; for(inti =0; i<len; ++i) {Pnode pnew = (pnode) malloc (sizeof(NODE));if(NULL= = pnew) {printf ("Memory allocation failed!" "); Exit (-1); } Pnew->pnext =NULL; Pnew->data = A[i];if(NULL= = Phead) Ptail = Phead = pnew;//If the head pointer is empty, the new node is used as the head node.        ElsePtail = Ptail->pnext = pnew;//Otherwise the new node is connected to the original tail node as a new tail node, moving ptail}returnPhead;}
(b), reverse chain:

Due to the existence of the head node and the non-head node classification of the forward chain, we use a better reverse chain to create the linked list, each time a new node is inserted before the head node of the original linked list, as a new head junction, NULL is the first when the list is empty.

/ * Reverse Build chain * /Pnode Reversecreate_link (intBintLen) {Pnode phead = NULL;inti = len-1; for(i; i>=0; -i) {Pnode pnew = (pnode)malloc(sizeof(NODE));if(NULL = = pnew) {printf("failed to allocate memory");Exit(-1);        } pnew->data = A[i]; Pnew->pnext = Phead;//New node nodding to the front of the original head node.Phead = pnew;The //head pointer moves to the new head node .}returnPhead;}
second, reverse traversal and inversion:(a), the time complexity of a large list of reverse traversal algorithm:

We first set up a "pacesetter pointer" pEnd, the similar usage of "pacesetter" can be referred to my array elements in the odd-even sequence of the dead loop caused by the thinking
Pend point to the tail node, and then start from the head node to find the pacesetter position, find the output pend->data, pacesetter forward, cycle the above steps can be reversed to traverse the linked list. The code is as follows:

/*时间复杂度较高*/void BackTravOne_Link(PNODE pHead){    PNODE p;    =NULL;//标兵    while!= pHead)    {        for(p=pHead; p->!== p->pNext);        printf("%d\t",p->data);        = p;    }}
(b), the large space complexity of the chain list inverse traversal algorithm:

Because each output once pend->data,pend the front node must traverse once, did a lot of work hard wasted a lot of time. We've talked about it before: All data set motion algorithms can be solved by wasting space. If the memory space is large enough to save time, we can borrow the array to receive the linked list of data sequentially, and then the inverse output of the array, can solve the problem of complex time, the code is as follows:

void BackTravTwo_Link(PNODE pHead){    int Receive[MAX];    PNODE p = pHead;    int0;    for (i,p; p; ++i,p=p->pNext)        Receive[i] = p->data;    for(--i; i>=0; --i)        printf("%d\t",Receive[i]);}

But we also know that the way to solve the problem by wasting space is not the optimal method, so what is the optimal method??

(iii), the reverse traversal and inversion of the linked list algorithm:

For the reverse traversal of the linked list, we can not ensure that the time complexity and space complexity are small, then if we put the list upside down after the forward traversal, and then inverted the list back to the original list, as long as the inversion algorithm time complexity and space complexity is small enough, only need to call three functions to complete the reverse traversal.
So how do you turn a list upside down? In fact, the process of inversion is to delete the node and reverse the process of building the chain, but the deletion is only to disconnect the original predecessor after the drive relationship, does not release memory, but instead of the broken node as a reverse chain of new nodes to use.

1. Code:

/*由于最终倒置完成以后,头结点地址发生变化,所以要返回新的头结点地址。*/PNODE InversionWell_Link(PNODE pHead){    = pHead;    = q->pNext;    while(p)//当p指向NULL时,表明倒置完成,退出循环    {        q->= p->pNext;        p->= pHead;        = p;        = q->pNext;    }    return pHead;}

The inverted method is used to traverse the original linked list without adding new large memory and minimizing the complexity of the time. In the number of nodes in the list of thousands, the advantages are particularly prominent.
2. Illustrations:

Before and after inversion (assuming that the list has four nodes):

A complete node operation flow (the Green Line is the link established for that step, and the red line is the link broken by that step):


Third, test the complete code:
# include<stdio.h># include <stdlib.h># define MAXtypedef structnode{intData//Data fields    structNode * PNEXT;//Pointer field}node,*pnode; Pnode Forwardcreate_link (intBintLen);//forward build chainPnode Reversecreate_link (intBintLen);//Reverse Build chainvoidPrint_link (Pnode phead);//forward traversalvoidBacktravone_link (Pnode phead);//With pacesetter, reverse traversevoidBacktravtwo_link (Pnode phead);//using arrays, reverse traversalPnode Inversionwell_link (Pnode phead);//traverse by invertedintMain (void) {Pnode phead;//Head pointer, receive the address of the head node returned when creating the linked list    inta[8] = { A,Panax Notoginseng, the, $, -, About,8, One};printf("Create a successful linked list: \ n");//phead = Forwardcreate_link (a,8);Phead = Reversecreate_link (A,8); Print_link (Phead);printf("\ n");printf("Using the pacesetter" traversal: \ n "); Backtravone_link (Phead);printf("\ n");printf("using array traversal \ n"); Backtravtwo_link (Phead);printf("\ n");printf("linked list traversal with inverted list: \ n");    Phead = Inversionwell_link (Phead); Print_link (Phead);printf("Call once again the Inversionwell_link () function, inverted back to the original list: \ n");    Phead = Inversionwell_link (Phead); Print_link (Phead);printf("\ n");return 0;}/ * Positive Build chain * /Pnode Forwardcreate_link (intAintLen//Return value type is struct Node * type{Pnode phead, ptail; Phead = NULL; for(inti =0; i<len; ++i) {Pnode pnew = (pnode)malloc(sizeof(NODE));if(NULL = = pnew) {printf("Memory allocation failed!" ");Exit(-1);        } pnew->pnext = NULL; Pnew->data = A[i];if(NULL = = phead) Ptail = Phead = pnew;//If the head pointer is empty, the new node is used as the head node.        ElsePtail = Ptail->pnext = pnew;//Otherwise the new node is connected to the original tail node as a new tail node, moving ptail}returnPhead;}/ * Reverse Build chain * /Pnode Reversecreate_link (intBintLen) {Pnode phead = NULL;inti = len-1; for(i; i>=0; -i) {Pnode pnew = (pnode)malloc(sizeof(NODE));if(NULL = = pnew) {printf("failed to allocate memory");Exit(-1);        } pnew->data = A[i]; Pnew->pnext = Phead;//New node nodding to the front of the original head node.Phead = pnew;The //head pointer moves to the new head node .}returnPhead;}voidPrint_link (Pnode phead) {if(Phead = = NULL)printf("The list is empty!" "); for(Pnode p = phead; p; p = p->pnext)printf("%d\t", P->data);printf("\ n");}voidBacktravone_link (Pnode phead) {Pnode p; Pnode pEnd = NULL;//pacesetter     while(pEnd! = phead) { for(p=phead; P->pnext! = pEnd; p = p->pnext);printf("%d\t", P->data);    PEnd = p; }printf("\ n");}voidBacktravtwo_link (Pnode phead) {intReceive[max]; Pnode p = phead;inti =0; for(i,p; p; ++i,p=p->pnext) Receive[i] = p->data; for(I. i>=0; I.)printf("%d\t", Receive[i]);printf("\ n");}    Pnode Inversionwell_link (Pnode phead) {Pnode q = phead; Pnode p = q->pnext; while(p)//when p points to null, indicates that the inversion is complete and exits the loop{Q->pnext = p->pnext;        P->pnext = Phead;        Phead = p;    p = q->pnext; }returnPhead;}

Inverse traversal and inversion algorithm for linked list operation rules

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.