Reverse Linked List II
Posted copperface
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
.
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
.
分析
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; } } |
以上是关于Reverse Linked List II的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 92. Reverse Linked List II