数据结构算法 -- 翻转链表
程序员文章站
2022-06-28 17:11:45
领扣LintCode问题答案-36. 翻转链表 II目录36. 翻转链表 II鸣谢36. 翻转链表 II翻转链表中第m个节点到第n个节点的部分m,n满足1 ≤ m ≤ n ≤ 链表长度样例 1:输入: 1->2->3->4->5->NULL, m = 2 and n = 4,输出: 1->4->3->2->5->NULL.样例 2:输入: 1->2->3->4->NULL, m = 2 and n....
目录
翻转链表
翻转链表中第m个节点到第n个节点的部分
m,n满足1 ≤ m ≤ n ≤ 链表长度
样例 1:
输入: 1->2->3->4->5->NULL, m = 2 and n = 4,
输出: 1->4->3->2->5->NULL.
样例 2:
输入: 1->2->3->4->NULL, m = 2 and n = 3,
输出: 1->3->2->4->NULL.
import java.util.Stack; /**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/ public class Solution { /**
* @param head: ListNode head is the head of the linked list
* @param m: An integer
* @param n: An integer
* @return: The head of the reversed ListNode
*/ public ListNode reverseBetween(ListNode head, int m, int n) { // write your code here if (n == m) { return head; } ListNode mNode = head; ListNode tempH = head; int i = 1; while (i < m) { tempH = tempH.next; i++; mNode = tempH; } Stack<ListNode> stack = new Stack<>(); while (i < n) { tempH = tempH.next; i++; stack.push(tempH); } for (int j = 0; j <= (n - m) / 2; j++) { tempH = stack.pop(); int tempV = mNode.val; mNode.val = tempH.val; tempH.val = tempV; mNode = mNode.next; } return head; } }