1. Enter the head node of a linked list, reverse the list, and return the head node of the inverted list.
The linked table node is defined as follows:
struct ListNode
{
int M_nkey;
listnode* m_pnext;
};
analysis: This is a widely circulated Microsoft face test. Since this problem can be a good response to the programmer's thinking is tight, after Microsoft has been a lot of companies in the interview with this problem.
int Reversesinglylistnode (ListNode *list) { listnode *newlist; The head node of the new linked list lnode *p,*q; Point to the first node of List, that is, the node p=list to be removed ; Null if parameter is empty or memory allocation fails (p = = NULL | | (NewList = (ListNode *) malloc (sizeof (lnode))) = = null) { return null; } Initialize newlist newlist->next = NULL; The first node of the list is placed in turn at the first node of the newlist while (p->next! = NULL) { q = p->next; Newlist->next = p->next; Head Insertion Method p=newlist->next; p=q; } The original head node should be released and the pointer to the new head node should be free (p); return newlist;}
The second method is to place the node after the first node behind the list each time, which is the original single-linked list.
In order to reverse the single-linked list, we first make the next field of the head node point to Node 2, then the next field of node 1 points to Node 3, and finally the next field of node 2 points to Node 1, the first Exchange is completed, the order becomes the header-Node 2-Node 1-node 3-node 4-null, Then do the same exchange to move the node 3 to the front of Node 2, and then the node 4 moved to the front of the node 3 to complete the reversal, the idea has, it should write code:
int reversesinglylinkedlist (ListNode *list) { lnode *p = NULL; Lnode *q = NULL; if (list = = null) return null; p = list->next; while (p->next! = NULL) { q = p->next; P->next = q->next; Q->next = list->next; List->next = q; } return list;}
Data structure and algorithm-linked list inversion lead node