[Algorithm exercise] Reverse linked list, list sort, delete node

Source: Internet
Author: User
Tags prev

Reverse Reset:

Use recursion

Consider the recursive algorithm, if there is only one node, then directly return, if there are two nodes (A1,A2) need to do the operation is://a2->next=a1;a1->next=null;return A2;//A2 is the new head node, if there are three nodes, The sub-chain (A2,A3) should first be reversed and return the new head node of the child chain, and then the chain (A2,A3) as a composite node A2 ',//composition of the new two-tuple (A1,A2 ') and then you can do the same thing before: A2 '->next=a1;a1-> Next=null;return A3 '; can, more than one node can be similarly obtained void REVERSELIST_DG (node* pcur,node** listhead)  {  if (NULL = = pcur) | | (NULL = = Pcur->next))      {          *listhead = pcur;      }      else      {          node* pnext = pcur->next;          REVERSELIST_DG (Pnext,listhead); Returns the new head node of the subsequent node        pnext->next = pcur;            Points the successor node to the current node.          pcur->next = NULL;      }  }  

Normal:

It is best to draw an understanding of the next void Reverselist_mf (NODE **head) {printf ("Begin to Reverse the List from mallocfree\n"); if (head = = NULL | | (*head)->next = = NULL | | *head = = NULL) {printf ("This list num <= 2\n"); return;} node* ppre = *head;    Previous pointer      node* pcur = ppre->next;  Current pointer      node* pnext = NULL;       Successor pointer while      (pcur!=null)      {          Pnext = pcur->next;          Pcur->next = Ppre;  Put the current point to the front one, this time to realize the reverse.        Ppre = pcur;          Pcur = Pnext;      }  (*head)->next = NULL;  *head = Ppre;        Record the new head node  }
Last image: The picture is a bit big ...



The second one:



There's another one: it's almost like this.

void Reverselist_new (node** phead) {printf ("Begin to Reverse the List New \ n"); if (Phead = = NULL | | (*phead)->next = = NULL)    {        return;    }     node* PRev = NULL;    node* pcur = *phead;    while (pcur! = NULL)    {        node* ptemp = pcur;           Pcur = pcur->next;               Ptemp->next = PRev;              PRev = ptemp;    } Return prev;//returns the new head node (*phead)->next = Null;*phead = PRev;}

Delete:

See in the original:

Http://www.cnblogs.com/bakari/p/4013812.html

Delete a node in a single-linked list with the time complexity of O (1)

This is a widely circulated Google interview questions, to examine our operation and time complexity of the list of the understanding of the problem, I can not think of a better solution, but others put the problem in this, there must be a solution. General single-linked list to delete a node, you need to know the node to delete the previous node, you need O (n) traversal time, obviously conventional thinking is not. In a closer look at the topic, a different way of thinking, since can not be in O (1) to delete the previous element of the node, but we can easily get the latter element, so that we do not assign the latter element to the node to be deleted, so that is equivalent to the deletion of the current element. Visible, this method is feasible, but if the node to be deleted is the last node, then can not follow the above thought, there is no way, can only follow the usual method of traversal, time complexity of O (n), is not meet the requirements of the topic? Probably a lot of people in this will be suspicious of their own thinking, so abandon this idea, and finally may give up the problem, this is the interesting place of the question, although see simple, but examined the analysis of the ability of judgment, whether have a strong psychological, full confidence. In fact, we analyze, still satisfies the topic request, if the deletion node is the front n-1 node, the time complexity is O (1), only the deletion node is the last one, the time complexity is O (n), so the average time complexity is: (O (1) * (n-1) + O (n))/n = O (1) ; still O (1). See the code below:

void List_deletenode_google (node *plisthead, node *ptobedeleted) {     if (!plisthead | |!ptobedeleted)         return;     if (ptobedeleted->data! = NULL) {  NODE *pnext = ptobedeleted->next; Ptobedeleted->next = pnext->next; pTo Bedeleted->data = pnext->data;         Delete Pnext;        Pnext = NULL;     }     else {//the node to be deleted is the tail node         *ptemp = Plisthead; while (ptemp->next! = ptobedeleted)  ptemp = ptemp->next; ptemp-& Gt;next = NULL;        Delete ptobedeleted;        ptobedeleted = NULL;    } plisthead->listlen--;}



Sort

I used the Select sort

Sort/********************************* List *******************************************//* ==========================  Function: Select sort (from small to Large) return: pointer to list header ========================== The basic idea of selecting sort is to select the key value (that is, the field with which it is sorted, and we take the number num as the key value) from the node that is not yet sequenced.   Regroup into a linked list in turn.  I think the key to this kind of program is to understand: Head stores the address of the first node, Head->next stores the address of the second node, and the address of any node p can only be obtained by the next of its previous node. One-way list selection sort diagram:---->[1]---->[3]---->[2] ...----> [n]---->[null] (original linked list) head 1->next 3->next 2-> Next n->next---->[null] (empty list) First tail---->[1]---->[2]---->[3] ...---->[n]---->[null] (sorted list) First 1->next 2->next 3->next Tail->next 1, firstly find the smallest in the original list, find one and then put it into another empty list; 2. The empty list places the first incoming node, produces an ordered list, and lets It is separated from the original list (note that the original linked list is the first node or the other node in the middle); 3, continue to find the next smallest in the original linked list, find and then put it into the ordered list of the tail pointer next, then it becomes its tail pointer; */node* Selectsort (pnode *head) {if (head = = NULL | | *head = = NULL | |    (*head)->next = = null) return null;      NODE *pfirst;       /* table head pointer with ordered chain */NODE *ptail; /* End-of-order pointer with ordered chain */NODE *pminbefore;        /* The pointer to the predecessor node of the node with the smaller key value, */node *pmin;           /* Store Minimum nodes */node *p;      /* node currently being compared */Pfirst = NULL; while (*head! = NULL)/* Find the node with the lowest key value in the linked list. */{/* Note: Here the For statement is the place to select the sorting idea */for (P = *head, pmin = *head; P->next! = NULL; p = p->next)/* Iterate through the nodes in the linked list to find the smallest node at this time. */{if (P->next->data < pmin->data)/* Find a node smaller than the current min.           */{pminbefore = p; /* Save the found node's precursor node: Obviously P->next's precursor node is p.     */pmin = p->next; /* Save nodes with small key values. */}}/* After the For statement ends, you have to do two things, one is to put it into an ordered list, and the other is to make it leave the original linked list according to the corresponding conditions.              */* First thing */if (Pfirst = = NULL)/* If the ordered list is currently an empty list */{      Pfirst = Pmin;                          /* Find the node with the lowest key value for the first time.      */ptail = pmin;                /* Note: The tail pointer makes it point to the last node.       */} else/* There are already nodes in the ordered list                         */{ptail->next = pmin;/* Put the smallest node you just found at the end, i.e. let the tail pointer next point to it.       */ptail = pmin;                                  /* The tail pointer also points to it.              */}/* The second thing */if (pmin = = *head)/* If the smallest node found is the first node */{   *head = (*head)->next; /* Obviously let head point to the original Head->next, that is, the second node, OK */} else/* If it is not the first node */{pminbefore-& Gt;next = pmin->next; /* Next of the last minimum node points to the current pmin next, so that Pmin leaves the original linked list. */}} if (Pfirst! = NULL)/* Loop ends Get ordered list First */{Ptail->next = N ULL;      /* The next of the last node of the unidirectional list should point to NULL */} *head = Pfirst;  return *head;   }


All code:

#include <stdio.h>const int n=6;    typedef struct _node{//single-linked list int data;      int Listlen;  struct _node* next;  }node,*pnode;    Create a single-linked list from an array pnode createlist (int a[n]) {printf ("Begin to create the list\n");      node* listhead=new NODE ();      listhead->data=a[0];      listhead->next=null;          for (int i=n-1;i>=1;i--) {node* p=new NODE ();  p->data=a[i];        P->listlen = N;          p->next=listhead->next;      listhead->next=p;    }//listhead->listlen = N;  return listhead; }///Output single-linked list void printlist (Pnode listhead) {if (null==listhead) {printf ("The List is empty!");    return;}          else {node* p=listhead;            while (P!=null) {printf ("%d", p->data);          p=p->next;  }} printf ("\ n");} void Reverselist_new (node** phead) {printf ("Begin to Reverse the List New \ n"); if (Phead = = NULL | |    (*phead)->next = = NULL) {return;    } node* PRev = NULL; Node* pcur = *phead;           while (pcur! = NULL) {node* ptemp = pcur;               Pcur = pcur->next;              Ptemp->next = PRev;    PRev = ptemp; }//return prev;//Returns a new head node (*phead)->next = Null;*phead = PRev;} Consider the recursive algorithm, if there is only one node, then directly return, if there are two nodes (A1,A2) need to do the operation is://a2->next=a1;a1->next=null;return A2;//A2 is the new head node, if there are three nodes, The sub-chain (A2,A3) should first be reversed and return the new head node of the child chain, and then the chain (A2,A3) as a composite node A2 ',//composition of the new two-tuple (A1,A2 ') and then you can do the same thing before: A2 '->next=a1;a1-> Next=null;return A3 '; can, more than one node can be similarly obtained void REVERSELIST_DG (node* pcur,node** listhead) {if (NULL = = pcur) | |      (NULL = = Pcur->next))      {*listhead = Pcur;          } else {node* Pnext = pcur->next; REVERSELIST_DG (Pnext,listhead);            Returns the new head node of the subsequent node pnext->next = Pcur;          Points the successor node to the current node.      Pcur->next = NULL; }}//Best draw to understand the next void Reverselist_mf (NODE **head) {printf ("Begin to Reverse the List from mallocfree\n"); if (head = = NULL | | (*head)->next = = NULL | | *head = = NULL) {printf ("This list num <= 2\n"); return;}    node* ppre = *head;  Previous pointer node* pcur = ppre->next;       Current pointer node* pnext = NULL;          Successor pointer while (pcur!=null) {pnext = pcur->next;  Pcur->next = Ppre;        Put the current point to the front one, this time to realize the reverse.          Ppre = Pcur;      Pcur = Pnext;  } (*head)->next = NULL;        *head = Ppre; Record the new header node}void list_delenode (pnode* list,int pos) {if (List! = NULL) && (0 <= Pos) && (Pos < (*li ST)->listlen)//&& ((*list)->next! = null)) {if ((*list)->next = = null) {return;} node* p = *list; Node *PB = null;for (int i = 0; I <= pos-1; i++)//Let P point to POS node, PB points to n-1 node {PB = P;p = P->next;} Pb->next = p->next;//The pointer to the previous node of the node to be deleted points to the next node to delete node//Decrease one node (*list)->listlen--;d elete[] p;} return;} Pnode List_getnode (pnode* list,int pos) {if (list! = NULL) && (0 <= Pos) && (Pos < (*list)->listl EN) {NODE *p = *list;for (int i = 0; i < pos-1; i++) {p = p->next;} return p;} return NULL;} /* General single-linked list to delete a node, you need to know the node to delete the previous node, you need O (n) traversal time, obviously conventional thinking is not. In a closer look at the topic, a different way of thinking, since can not be in O (1) to delete the previous element of the node, but we can easily get the latter element, so that we do not assign the latter element to the node to be deleted, so that is equivalent to the deletion of the current element. Visible, this method is feasible, but if the node to be deleted is the last node, then can not follow the above thought, there is no way, can only follow the normal method of traversal, the time complexity of O (n) */void list_deletenode_google (node *plisthead, node *     ptobedeleted) {if (!plisthead | |!ptobedeleted) return; if (ptobedeleted->data! = NULL) {NODE *pnext = ptobedeleted->next; Ptobedeleted->next = pnext->next; pToBeDe         Leted->data = pnext->data;        Delete Pnext;     Pnext = NULL; } else {//the node to be deleted is the tail node *ptemp = Plisthead; while (ptemp->next! = ptobedeleted) ptemp = ptemp->next; p        Temp->next = NULL;        Delete ptobedeleted;    ptobedeleted = NULL; } plisthead->listlen--;}   Sort/********************************* List *******************************************//* ========================== Function: Select sort (from small to Large) return: pointer to list header ========================== The basic idea of selecting a sort is to repeatedly select the key value from those nodes that are not yet sequenced (that is, use itSorted fields, we take the number num as the key value) the smallest node, and then regroup into a linked list.  I think the key to this kind of program is to understand: Head stores the address of the first node, Head->next stores the address of the second node, and the address of any node p can only be obtained by the next of its previous node. One-way list selection sort diagram:---->[1]---->[3]---->[2] ...----> [n]---->[null] (original linked list) head 1->next 3->next 2-> Next n->next---->[null] (empty list) First tail---->[1]---->[2]---->[3] ...---->[n]---->[null] (sorted list) First 1->next 2->next 3->next Tail->next 1, firstly find the smallest in the original list, find one and then put it into another empty list; 2. The empty list places the first incoming node, produces an ordered list, and lets It is separated from the original list (note that the original linked list is the first node or the other node in the middle); 3, continue to find the next smallest in the original linked list, find and then put it into the ordered list of the tail pointer next, then it becomes its tail pointer; */node* Selectsort (pnode *head) {if (head = = NULL | | *head = = NULL | |    (*head)->next = = null) return null;      NODE *pfirst;       /* table head pointer with ordered chain */NODE *ptail;  /* End-of-order-chain indicator */NODE *pminbefore;        /* The pointer to the predecessor node of the node with the smaller key value, */node *pmin;           /* Store Minimum nodes */node *p;      /* node currently being compared */Pfirst = NULL; while (*head! = NULL)/* Find the node with the lowest key value in the linked list. */{* * Note: thisThe For statement is the place where you choose the sorting idea, */for (P = *head, pmin = *head; P->next! = NULL; p = p->next)/* Loop through the nodes in the list to find the smallest node at this time. */{if (P->next->data < pmin->data)/* Find a node smaller than the current min.           */{pminbefore = p; /* Save the found node's precursor node: Obviously P->next's precursor node is p.     */pmin = p->next; /* Save nodes with small key values. */}}/* After the For statement ends, you have to do two things, one is to put it into an ordered list, and the other is to make it leave the original linked list according to the corresponding conditions.              */* First thing */if (Pfirst = = NULL)/* If the ordered list is currently an empty list */{      Pfirst = Pmin;                          /* Find the node with the lowest key value for the first time.      */ptail = pmin;                /* Note: The tail pointer makes it point to the last node. */} else/* There are already nodes in the ordered list */{PTA Il->next = Pmin; /* Put the smallest node you just found at the end, i.e. let the tail pointer next point to it.       */ptail = pmin;                                  /* The tail pointer also points to it.            */          }/* The second thing */if (pmin = = *head)/* If the smallest node found is the first node */{*head = (*he   AD)->next; /* Obviously let head point to the original Head->next, that is, the second node, OK */} else/* If it is not the first node */{pminbefore-& Gt;next = pmin->next; /* Next of the last minimum node points to the current pmin next, so that Pmin leaves the original linked list. */}} if (Pfirst! = NULL)/* Loop ends Get ordered list First */{Ptail->next = N ULL;      /* The next of the last node of the unidirectional list should point to NULL */} *head = Pfirst;  return *head;      } int main () {int a[n] = {5,7,2,4,10,1};      node* list = CreateList (a);  Printlist (list);  Recursive method node* ptemp = list;    printf ("Begin to Reverse the List from recursion \ n");  REVERSELIST_DG (ptemp,&list);  Printlist (list); Common method REVERSELIST_MF (&list); Printlist (list);//Common Method 2reverselist_new (&list); Printlist (list);//delete node printf ("Delete Second nodes\n"); List_delenode (&list,1); Printlist (list);//delete node printf ("Del node from Google--DeleTe second nodes\n "); List_deletenode_google (List,list_getnode (&list,2)); Printlist (list);//select Sort printf ("selectsort\n"); Selectsort (&list);    Printlist (list);   GetChar ();}


[Algorithm exercise] Reverse linked list, list sort, delete node

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.