题目描述:
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.
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */
代码:
1 class Solution { 2 public: 3 ListNode *reverseBetween(ListNode *head, int m, int n) { 4 //短路原则 5 if(head==nullptr || m>=n || n<1) 6 return head; 7 ListNode dummy = ListNode(-1); 8 dummy.next = head; 9 ListNode *pre = nullptr; 10 ListNode *p = &dummy; 11 int cnt = 0;//由于这里是从左往右的第几个节点,所以直接数出来就可以了 12 //每遇到一个非空节点,更新一下计数值 13 //按照前进步数的方法在m=1时不用走就到达了,会出现错误 14 while(p!=nullptr) 15 { 16 cnt++; 17 if(cnt == m) 18 pre = p; 19 if(cnt == n+1) 20 break; 21 p = p->next; 22 } 23 if(p==nullptr) 24 return head; 25 ListNode *next = p->next; 26 p->next = nullptr; 27 ListNode *cur = pre->next; 28 pre->next = nullptr; 29 pre->next = reverseList(cur); 30 cur->next = next; 31 return dummy.next; 32 } 33 34 ListNode *reverseList(ListNode *head) 35 { 36 if(head==nullptr || head->next==nullptr) 37 return head; 38 ListNode *last = nullptr; 39 ListNode *cur = head; 40 while(cur!=nullptr) 41 { 42 ListNode * temp = cur->next; 43 cur->next = last; 44 last = cur; 45 cur = temp; 46 } 47 return last; 48 49 } 50 51 };
原文地址:https://www.cnblogs.com/zjuhaohaoxuexi/p/11780106.html
时间: 2024-11-07 20:00:46