Title Description:
Reverse a linked list from position m to N. Do it in-place and in One-pass.
For example:
Given 1->2->3->4->5->NULL , m = 2 and n = 4,
Return 1->4->3->2->5->NULL .
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤length of list.
Problem Solving Ideas:given a linked list, it is required to reverse the sub-linked list from the M node to the nth node, requiring one complete scan to complete and no additional space
The M,n satisfies the 1<=m<=n<= chain table length.
First determine the sub-linked list to reverse the end-to-end node, the chain list to carry out a separate reversal. After the reversal is completed, the chain is returned to the original linked list. In the program, with P for the previous node to flip, that is, the first node m-1, with S for n+1 nodes, with PP to flip the tail of the sub-sequence node, that is, the nth node. After flipping, p points to the sub-sequence header after the flip, and the subsequence tail pp points to the back of the node s not flipped.
The code is as follows:
listnode* Reversebetween (listnode* head, int m, int n) { if (head==null| | Head->next==null) return head;if (m==n) return head; ListNode *p=head,*p1=head,*p2,*p3,*s,*pp;p2=p1->next;for (int i=1;i<n;i++) {if (i==m-1) p=p1;if (i<m) {p1=p2; P2=p1->next;} Else{if (i==m) {pp=p1;} P3=P2->NEXT;P2->NEXT=P1;P1=P2;P2=P3;} if (i==n-1) s=p2;} if (m==1) {head->next=s;head=p1;} Else{p->next=p1;pp->next=s;} return head; }
The complete code is as follows:
#include <iostream>using namespace std;struct listnode {int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}}; ListNode * Creatlist (); listnode* Reversebetween (listnode* head, int m, int n); void Main () {ListNode *head=creatlist (); ListNode *p=head;while (p) {cout<<p->val<< "";p =p->next;} cout<<endl; ListNode *head1=reversebetween (Head, 2, 4);p =head1;while (p) {cout<<p->val<< "";p =p->next;}} ListNode * Creatlist () {ListNode *head= (listnode*) malloc (sizeof (ListNode)); ListNode *p,*s;p=head;int X,cycle=1;while (cycle) {cin>>x;if (x!=0) {s= (listnode*) malloc (sizeof (ListNode)); s >val=x;p->next=s;p=s;} else cycle=0;} Head=head->next;p->next=null;return Head;} listnode* Reversebetween (listnode* head, int m, int n) {if (head==null| | Head->next==null) return head;if (m==n) return head; ListNode *p=head,*p1=head,*p2,*p3,*s,*pp;p2=p1->next;for (int i=1;i<n;i++) {if (i==m-1) p=p1;if (i<m) {p1=p2; P2=p1->next;} Else{if (i==m){PP=P1;} P3=P2->NEXT;P2->NEXT=P1;P1=P2;P2=P3;} if (i==n-1) s=p2;} if (m==1) {head->next=s;head=p1;} Else{p->next=p1;pp->next=s;} return head;}
Running results such as:
Reverse Linked List II