首页 > 代码库 > Reverse Linked List II
Reverse Linked List II
Reverse a linked list from position m to n.
Reverse a linked list from position m to n.
Notice
Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
ExampleGiven 1->2->3->4->5->NULL
, m = 2
and n = 4
, return 1->4->3->2->5->NULL
.
来源: http://www.lintcode.com/en/problem/reverse-linked-list-ii/
Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
Given 1->2->3->4->5->NULL
, m = 2
and n = 4
, return 1->4->3->2->5->NULL
.
来源: http://www.lintcode.com/en/problem/reverse-linked-list-ii/
分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | /** * 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 ListNode nhead = new ListNode(- 1 ); ListNode h = nhead; h.next = head; ListNode l1 = head, l2; int count = 1 ; while (count < m){ h = l1; l1 = l1.next; count++; } //h l1 //1->2<-3->4->5->NULL ListNode last = null ; while (count < n){ ListNode tmp = l1.next; l1.next = last; last = l1; l1 = tmp; count++; } //h L l1 //1->2<-3->4->5->NULL ListNode end = l1.next; //h L l1 e //1->2<-3->4->5->NULL l1.next = last; //h L l1 e //1->2<-3<-4 5->NULL h.next.next = end; //h L l1 e //1->2<-3<-4 5->NULL // |________| h.next = l1; return nhead.next; } } |
null
Reverse Linked List II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。