博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
反转链表II
阅读量:3958 次
发布时间:2019-05-24

本文共 1970 字,大约阅读时间需要 6 分钟。

题目来源

题目描述

在这里插入图片描述

解答一(递归)

需要两个不同指针,一个指向第 m 个结点,另一个指向第 n 个结点。一旦有了这两个指针,我们就可以不断地交换这两个指针指向结点的数据,并将两个指针相向移动,就像字符串的情况那样。然而,链表中没有向后指针,也没有下标。因此,我们需要使用递归来 模拟 向后指针。递归中的回溯可以帮助我们模拟一个指针从第n个结点向中心移动的移动过程。

class Solution {
private ListNode left; private boolean stop; public ListNode reverseBetween(ListNode head, int m, int n) {
this.left=head; this.stop=false; this.recurseAndRrverse(head,m,n); return head; } public void recurseAndRrverse(ListNode right,int m,int n){
if(n==1){
return; } right=right.next; if(m>1){
this.left=this.left.next; } recurseAndRrverse(right,m-1,n-1); if(this.left==right||right.next==this.left){
this.stop=true; } if(!this.stop){
int i=this.left.val; this.left.val=right.val; right.val=i; this.left=this.left.next; } }}

解答二(迭代)

class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
// Empty list if (head == null) {
return null; } // Move the two pointers until they reach the proper starting point // in the list. ListNode cur = head, prev = null; while (m > 1) {
prev = cur; cur = cur.next; m--; n--; } // The two pointers that will fix the final connections. ListNode con = prev, tail = cur; // Iteratively reverse the nodes until n becomes 0. ListNode third = null; while (n > 0) {
third = cur.next; cur.next = prev; prev = cur; cur = third; n--; } // Adjust the final connections as explained in the algorithm if (con != null) {
con.next = prev; } else {
head = prev; } tail.next = cur; return head; }}

转载地址:http://nnlzi.baihongyu.com/

你可能感兴趣的文章
类结构定义
查看>>
Windows下关于多线程类 CSemaphore,CMutex,CCriticalSection,CEvent,信号量CSemaphore的使用介绍
查看>>
图像处理基本算法(汇总)以及实现
查看>>
C++编程获取本机网卡信息 本机IP 包括Windows和Linux
查看>>
23种设计模式详解及C++实现
查看>>
C++连接CTP接口实现简单量化交易
查看>>
服务端使用c++实现websocket协议解析及通信
查看>>
C# string.Format使用说明
查看>>
Linux下安装Mysql数据库开发环境
查看>>
Linux用户及用户组添加和删除操作
查看>>
通用 Makefile 的编写方法以及多目录 makefile 写法
查看>>
C++的4种智能指针剖析使用
查看>>
RPC框架实现之容灾策略
查看>>
Docker私库
查看>>
hdu——1106排序(重定向)
查看>>
hdu——1556Color the ball(树状数组)
查看>>
hdu——1541Stars(树状数组)
查看>>
快速幂的精简代码
查看>>
求大数乘方的前n位数字(对数加快速幂)
查看>>
hdu——2602Bone Collector(第一类背包问题)
查看>>