题目描述
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:Given1->2->3->4->5->NULL, m = 2 and n = 4,return1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:1 ≤ m ≤ n ≤ length of list.
解题思路:
1)找到要翻转区间的第一个结点并记录该结点的前一个结点pre
2)找到要翻转区间的最后一个结点
3)翻转区间的链表,并保证后续的链表正确连接在链上
4)将翻转的第一个结点的前一结点与链表连接(分为两种情况,一种pre为空则返回翻转后链表,一种不为空,则连接,然后返回head)
1 #include <iostream> 2 #include <malloc.h> 3 using namespace std; 4 5 struct ListNode { 6 int val; 7 ListNode *next; 8 ListNode(int x) : val(x), next(NULL) {} 9 }; 10 /*在链表的末端插入新的节点,建立链表*/ 11 ListNode *CreateList(int n) 12 { 13 ListNode *head; 14 ListNode *p,*pre; 15 int i; 16 head=(ListNode *)malloc(sizeof(ListNode)); 17 head->next=NULL; 18 pre=head; 19 for(i=1;i<=n;i++) 20 { 21 p=(ListNode *)malloc(sizeof(ListNode)); 22 cin>>p->val; 23 pre->next=p; 24 25 pre=p; 26 } 27 p->next=NULL; 28 29 return head->next;//不带空的头结点 30 } 31 /*-------------------------输出链表-----------------------------------*/ 32 void PrintList(ListNode *h) 33 { 34 ListNode *p; 35 36 p=h;//不带空的头结点 37 while(p) 38 { 39 cout<<p->val<<" "; 40 p=p->next; 41 cout<<endl; 42 } 43 } 44 class Solution { 45 public: 46 //例 1->2->3->4->5->6->NULL m=2 n=5 47 ListNode *reverseBetween(ListNode *head, int m, int n) { 48 if(head == NULL) 49 return NULL; 50 51 ListNode *pNode = head; 52 ListNode *pre =NULL; 53 54 for(int i=1;i<m;i++) 55 { 56 pre = pNode; 57 pNode = pNode->next; 58 } 59 ListNode *last = pNode; 60 for(int i=m;i<n;i++) 61 { 62 last = last->next; 63 } 64 //翻转pNode last之间的结点 65 for(int i=0;i<n-m;i++) 66 { 67 ListNode *temp = pNode->next; 68 pNode->next = last->next; 69 last->next = pNode; 70 71 pNode = temp; 72 } 73 if(pre == NULL) 74 return last; 75 else 76 { 77 pre->next = last; 78 return head; 79 } 80 } 81 82 83 }; 84 int main() 85 { 86 int n1; 87 ListNode *h; 88 cout<<"输入链表1的结点数目"<<endl; 89 cin>>n1; 90 h = CreateList(n1); 91 cout<<"链表1为:"<<endl; 92 PrintList(h); 93 Solution s; 94 s.reverseBetween(h,2,5); 95 cout<<"翻转后:"<<endl; 96 PrintList(h); 97 98 }