标签:font put lan struct out for div turn lis
https://leetcode.com/problems/reverse-linked-list-ii/
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if(!head) return NULL; int num = m - 1; ListNode *dummy = new ListNode(-1); ListNode *st = dummy, *ans = st;; dummy -> next = head; ListNode *slow = head; n -= m, m -= 1; while(m --) slow = slow -> next; ListNode *cur = slow; while(n --) cur = cur -> next; ListNode *end = cur -> next; cur -> next = NULL; slow = reverseList(slow); ListNode *fast = slow; while(fast -> next) fast = fast -> next; fast -> next = end; while(num --) st = st -> next; st -> next = slow; return ans -> next; } ListNode *reverseList(ListNode *c) { if(!c || !c -> next) return c; ListNode *New = reverseList(c -> next); c -> next -> next = c; c -> next = NULL; return New; } };
分三段 然后拼在一起 但是写的乱糟糟 大概写了一个多小时 我恨!自己不争气 落泪
FH
#Leetcode# 92. Reverse Linked List II
标签:font put lan struct out for div turn lis
原文地址:https://www.cnblogs.com/zlrrrr/p/10409250.html