The task is reversing a list in range m to n () or a whole list (206).
All in one:u need three pointers to achieve this goal.
1) Pointer to last value
2) Pointer to cur p value
3) Pointer to next value
Here, showing my code wishes can help U.
#include <iostream>#include<cstdio>#include<cstring>using namespaceStd;typedefstructListNode {intVal; ListNode*Next; ListNode (intx): Val (x), Next (NULL) {}}listnode,*Pnode;voidcreate_list (Pnode head) {Pnode P=Head; intN; CIN>>N; for(inti =0; i < n; i + +){ intT; CIN>>T; if(i = =0) {Headval =T; HeadNext =NULL; cout<<"Head is"<Endl; P=Head; }Else{pnode NewNode= (Pnode)malloc(sizeof(Pnode)); NewNodeval =T; NewNodeNext =NULL; PNext =NewNode; P=NewNode; cout<<"P is"<<p-val<<Endl; } }}voiddisplay (Pnode head) {Pnode P=Head; while(p) {cout<<p->val<<" -"; P= P-Next; }cout<<Endl;}classSolution { Public: ListNode* Reversebetween (listnode* head,intMintN) {if(m = = N | | head = = NULL)returnHead; ListNode*plast = head, *p = Head, Next, *pnext =NULL; ListNode*newn = null, *NEWM = null, *beforem = head, *aftern =NULL; intpos =1; while(p) {if(pos = = M-1) {Beforem=PLast; PLast=p; P= P-Next; } Else if(POS >= m && Pos <N) {Pnext= P-Next; PNext =PLast; if(pos = =m) {PLastNext =NULL; NEWM=PLast; } pLast=p; if(pos = = N-1) {newn=p; Aftern=Pnext; } P=Pnext; }Else{pLast=p; P= P-Next; } POS++; } if(m==1&& Aftern = =NULL) {Head=newn; }Else if(M = =1) {Head=newn; NEWMNext =Aftern; }Else{BeforemNext =newn; NEWMNext =Aftern; } returnHead; } ListNode* Reverselist (listnode*head) { if(head = = NULL)returnHead; ListNode*plast = head, *p = Head, Next, *pnext =NULL; while(p) {Pnext= P-Next; PNext =PLast; if(PLast = =head) {PLastNext =NULL; } pLast=p; P=Pnext; } head=PLast; returnHead; }};intMain () {Pnode head= (Pnode)malloc(sizeof(Pnode));; Create_list (head); cout<<"After creating, head is"<Endl; Display (head); Solution tmp=solution (); //Tmp.reversebetween (Head, 2, 3);Tmp.reverselist (head); System ("Pause"); return 0;}
"Leetcode" 92. Reverse Linked List II && 206. Reverse Linked List