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.

first 是第 m -1 个元素。 elementM是第m个元素。 后面将 cur -> second 变成 cur <- second。 最后 cur是第n个元素,second是第n + 1个元素。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode reverseBetween(ListNode head, int m, int n) {
14         // Start typing your Java solution below
15         // DO NOT write main() function
16         ListNode header = new ListNode(-1);
17         header.next = head;
18         ListNode cur = header;
19         ListNode first = null;
20         ListNode elementM = null;
21         ListNode second = null;
22         int i = 0;
23         while(i < m){
24             first = cur;
25             cur = cur.next;
26             i ++;
27         }
28         elementM = cur;
29         second = cur.next;
30         while(i < n){
31             ListNode tmp = second.next;
32             second.next = cur;
33             cur = second;
34             second = tmp;
35             i ++;
36         }
37         first.next = cur;
38         if(elementM != null && elementM != second) elementM.next = second;
39         return header.next;
40     }
41 }

 

第三遍:

 1 public class Solution {
 2     public ListNode reverseBetween(ListNode head, int m, int n) {
 3         ListNode header = new ListNode(-1);
 4         header.next = head;
 5         ListNode first = header, second = header;
 6         for(int i = 1; i < m; i ++){
 7             first = first.next; 
 8         }
 9         ListNode cur = first.next;
10         for(int i = 0; i < n; i ++){
11             second = second.next;
12         }
13         ListNode end = second;
14         second = second.next;
15         end.next = null;
16         while(cur != null){
17             ListNode tmp = cur.next;
18             cur.next = second;
19             second = cur;
20             cur = tmp;
21         }
22         first.next = end;
23         return header.next;
24     }
25 }

 

 

转载于:https://www.cnblogs.com/reynold-lei/p/3423690.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值