【LeetCode】92. 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

 

描述:

给出一个链表,要求将表中从位置m到n处的所有结点均逆置

 

分析:

第m到n的结点使用头插法逆序,然后接到原先的串上即可

 

代码:(时间复杂度O(n),空间复杂度O(1))

/**
 * 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) {
		ListNode* my_head = new ListNode(0);
		my_head->next = head;
		ListNode* first_node = my_head;
		int count = n - m + 1;
		while (-- m) {
			first_node = first_node->next;
		}
		
		ListNode* new_head = new ListNode(0);
		ListNode* new_tail = first_node->next;
		while(count --) {
			ListNode* temp = first_node->next;
			first_node->next = temp->next;
			
			temp->next = new_head->next;
			new_head->next = temp;;
		}
		new_tail->next = first_node->next;
		first_node->next = new_head->next;
		
		return my_head->next;
	}
};

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页