title : Define a function, enter the head node of a linked list, reverse the list and output the head node of the inverted list.
Analysis:
Header-by-head interpolation for reversal
Set 3 pointers: Head node, prev previous node, cur next node
Note: The linked list is empty, or only one node is in the case!
Code:
#include <iostream>using namespace Std;struct listnode{int val; ListNode *next; ListNode (int x): Val (x), Next (nullptr) {}};class solution{public:listnode* reverselist (listnode* phead) {if (Phead = = nullptr | | Phead->next = = nullptr) return phead; ListNode Dummy ( -1);d ummy.next = Phead; ListNode *head = &dummy; listnode* prev = head->next; listnode* cur = prev->next;do{prev->next = Cur->next;cur->next = Head->next;head->next = Cur;cur = prev ->next;} while (cur! = nullptr); return dummy.next;};
Sword refers to the code on the offer book:
Listnode* reverlist (listnode* phead) { listnode* preversehead = null; listnode* pnode = phead; listnode* pprev = null; while (PNode != NULL) { ListNode* pNext = pnode->m_next; if (pnext == null) preversehead = pnode; pNode->m_next = pPrev; pPrev = pNode; pnode = pnext; } return preversehead; }
Welcome to discuss the exchange!
This article is from the "pin-soil" blog, please be sure to keep this source http://3240611.blog.51cto.com/3230611/1617528
Reverse linked list-finger offer-16