leetcode--Reverse Linked List II

本文介绍了一种算法,用于在单次遍历中反转链表的一部分,即从位置m到n,并提供了一个Java实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

[java]  view plain  copy
  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * public class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { val = x; } 
  7.  * } 
  8.  */  
  9. public class Solution {  
  10.     public ListNode reverseBetween(ListNode head, int m, int n) {  
  11.         if(n==m) return head;  
  12.         if(m>n){  
  13.             int t = n;  
  14.             n = m;  
  15.             m = t;  
  16.         }  
  17.         ListNode h = head;        
  18.         ListNode res = new ListNode(-1);  
  19.         ListNode pre = res;  
  20.         pre.next = h;  
  21.         int count = 1;        
  22.         //pre为m前的值  
  23.         while(h!=null&&count<m){  
  24.             pre = pre.next;  
  25.             h = h.next;  
  26.             count++;  
  27.         }     
  28.         ListNode cur = h;//找到m对应的值        
  29.         ListNode fhead = new ListNode(-1);  
  30.         ListNode last = cur;//第一个,然后会成为最后一个  
  31.         while(count<=n){  
  32.             pre.next = cur.next;  
  33.             cur.next = fhead.next;  
  34.             fhead.next = cur;  
  35.             cur = pre.next;  
  36.             count++;  
  37.         }         
  38.         last.next = pre.next;  
  39.         pre.next = fhead.next;  
  40.         return res.next;  
  41.     }  
  42. }  


原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46444071

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值