Implement reverse linked list and reverse linked list
1. Question description
Enter a linked list. After the linked list is reversed, all elements of the linked list are output.
2. Code
(1) Code 1: store all the nodes in one stack, and use the features of the stack first and then pop up all of them to create a new linked list.
Struct ListNode {int val; struct ListNode * next; ListNode (int x): val (x), next (NULL) {}}; // -- implemented using a stack, listNode * ReverseList (ListNode * pHead) {if (! PHead) return NULL; stack
StackNode; ListNode * p = pHead; while (p) {stackNode. push (p); p = p-> next;} ListNode * pNewHead; pNewHead = new ListNode (stackNode. top ()-> val); stackNode. pop (); p = pNewHead; while (! StackNode. empty () {ListNode * pTemp = new ListNode (stackNode. top ()-> val); stackNode. pop (); p-> next = pTemp; p = p-> next;} return pNewHead ;}
(2) Code 2: when one node is reversed and another node is reversed, you need to record the previous node in advance and record the subsequent node, just loop and traverse again. This is easy to confuse. What is the last node of the first node? It is NULL, each time you traverse to the next node, you can store the current node as the previous node of the next node.
// Implementation after reading: directly implement ListNode * ReverseList1 (ListNode * pHead) {if (pHead = NULL) return NULL; if (pHead-> next = NULL) return pHead; ListNode * pNode = pHead; ListNode * pNodeEarly = NULL; ListNode * pRes = NULL; while (pNode) {ListNode * pNext = pNode-> next; // save the next node of the current node if (pNext = NULL) pRes = pNode; // The Last node pNode-> next = pNodeEarly; // The next of the current node is equal to the saved previous node pNodeEarly = pNode; // the current node is stored as the previous node pNode = pNext of the system; // Move the current node one down} return pRes ;}3. Note:
Pointer questions are not difficult in nature, but special attention must be paid to detailed operations, especially when the cursor is stopped, next operations, and special circumstances of the question. Therefore, when creating a linked list question, you must first think about it and then start it. You must be clear-minded and do not blindly do the question.