Java实现-翻转链表2

xiaoxiao2021-02-28  98

翻转链表中第m个节点到第n个节点的部分

 注意事项

m,n满足1 ≤ m ≤ n ≤ 链表长度

您在真实的面试中是否遇到过这个题?  Yes 样例

给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->nul

/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param ListNode head is the head of the linked list * @oaram m and n * @return: The head of the reversed ListNode */ public ListNode reverseBetween(ListNode head, int m , int n) { // write your code if(m==n){ return head; } ListNode dummy=new ListNode(-1); dummy.next=head; ListNode m_Pre=dummy; while(m>1){ m_Pre=m_Pre.next; m--; n--; } Stack<ListNode> stack=new Stack<ListNode>(); while(n>0){ ListNode node=m_Pre.next; m_Pre.next=node.next; node.next=null; stack.push(node); n--; } while(!stack.isEmpty()){ ListNode node=stack.pop(); node.next=m_Pre.next; m_Pre.next=node; m_Pre=m_Pre.next; } return dummy.next; } }

转载请注明原文地址: https://www.6miu.com/read-38281.html

最新回复(0)