leetcode微软面试题92Reverse Linked List II

来源:互联网 发布:淘宝男鞋排行榜 编辑:程序博客网 时间:2024/05/17 04:34

92. Reverse Linked List II

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

这道题的描述很简单大意就是:

给定一个链表,将链表的第m到第n个节点旋转,然后返回旋转后的链表

这道题很基础,也是很多大公司喜欢的面试题,其中解题思路有几个

借用上面举的例子

方法1:

1.1->2->3->4->5->6—>7->NULLm = 3 and n = 5,

将其中的m之前的尾插法插入到n之后,将n之后的头插法插到m之前

2.7->6->3->4->5->2->1->null

将所有节点再旋转一遍

3.1->2->5->4->3->6->7->null

方法2:

1.1->2->3->4->5->6—>7->NULLm = 3 and n = 5,

将m+1到n的元素依次头插法插入m之前的链表

2.1->2->4->3->5->6->7->null

3.1->2->5->4->3->6->7->null


public class ReverseLinkedListII2 { public static ListNode reverseBetween(ListNode head, int m, int n) { ListNode dummyhead = new ListNode(1) ; dummyhead.next = head; ListNode pre = dummyhead; ListNode cur = head; ListNode preM = dummyhead; for(int i = 1;i<=n;i++) { if(i==m) { pre = preM;//pre是第m-1个节点 } if(i>m && i<=n) { //删除当前节点,preM是第i-1个节点 preM.next = cur.next; //头插法插入m前面的部分 cur.next = pre.next; pre.next = cur; cur = preM;//这时候cur已经变化,所以得重新赋值  } preM = cur; //获取cur前面的节点;cur = cur.next;  }     return dummyhead.next;     } public static void main(String args[]) { ListNode head = new ListNode(1); ListNode head1 = new ListNode(2); ListNode head2 = new ListNode(3); head.next = head1; head1.next = head2; head2 = null; ListNode temp = reverseBetween( head, 2,3); while(temp != null) { System.out.println(temp.val); temp = temp.next; }  }}




0 0
原创粉丝点击