当前位置:网站首页>输入起始位置,终止位置截取链表
输入起始位置,终止位置截取链表
2022-08-11 03:00:00 【this is a book】
1 背景
输入 m n ,链表,得到 起始点为m,终点为n的链表
2 解题思路
1) 首先要会 根据输入的n,获取N节点 ,具体就查看这篇文章
https://blog.csdn.net/an13654067079/article/details/126173743
2)m节点,n节点 m节点作为新链表的表头
3) m节点的上一个节点 mPre.next = null
n节点的下一个节点 nNext.next = null
新的链表就被截取出来了,问题不难
public static void main(String[] args) {
ListNode listNode = ListNodeUtil.getListNode();
int m = 2;
int n = 4;
//获取m节点, n节点
ListNode mNode = index(listNode, m);
ListNode nNode = index(listNode, n);
if(m!=1){
//获取m的上一个节点
int mPre = m -1;
ListNode mPreNode = index(listNode, mPre);
mPreNode.next = null;
}
ListNode nNextNode = nNode.next;
nNode.next = null;
System.out.println(mNode);
}
/**
* 获取指定位置的节点
*
* @param listNode
* @param index
* @return
*/
public static ListNode index(ListNode listNode , int index){
ListNode dummyNode = new ListNode();
dummyNode.setVal(0);
dummyNode.setNext(listNode);
int n = 1;
for(int i = 0 ; i< index; i++){
dummyNode = dummyNode.getNext();
}
return dummyNode;
}
import lombok.Data;
@Data
public class ListNode {
/**
* 当前节点值
*/
public int val;
/**
* 下一个节点
*/
public ListNode next ;
}
public class ListNodeUtil {
/**
* 获取链表
*
* @return
*/
public static ListNode getListNode(){
ListNode one = new ListNode();
one.setVal(1);
ListNode two = new ListNode();
two.setVal(2);
ListNode three = new ListNode();
three.setVal(3);
ListNode four = new ListNode();
four.setVal(4);
ListNode five = new ListNode();
five.setVal(5);
one.setNext(two);
two.setNext(three);
three.setNext(four);
four.setNext(five);
return one;
}
}
边栏推荐
猜你喜欢
ESP32的环境配置(arduino arduino2.0 VScode platform哪个好用?)
学军中学推理社2017届招新试题
Ten Advanced Concepts of SQL Development
flink The object probably contains or references non serializable fields.
添加用户报错useradd: cannot open /etc/passwd
ES进阶 函数功能语法新特性详解
OpenCV创始人:开源绝不能完全免费!
解决vim与外界的复制粘贴(不用安装插件)
[BX]和loop
The problem that Merge will be lost again after code Revert has been solved
随机推荐
行业的思考
ifconfig与ip命令的比较
带你系统学习MySQL索引
Typescript学习笔记 | 字节青训营笔记
Goodbye Chengdu paper invoices!The issuance of electronic invoices for accommodation expenses will soon completely replace the invoices of hotels, catering and gas stations
深度学习-第二次
font
leetcode: 358. Reorder strings at K distance intervals
IDE compilation error: Dangling metacharacter
Logstash日志数据写入异常排查问题总结
CC0 vs. commercial IP: which model is better for NFTs?
四大组件---ContentResolver
A surviving spouse of the opposite sex within large turn paragraph, what for
最倒霉与最幸运
①CAS SSO单点登录框架源码深度分析
YTU 2418: C语言习题 矩阵元素变换
this question in js
LitePal操作数据库
flink The object probably contains or references non serializable fields.
Docker 链接sqlserver时出现en-us is an invalid culture错误解决方案