当前位置:网站首页>输入起始位置,终止位置截取链表
输入起始位置,终止位置截取链表
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;
}
}
边栏推荐
猜你喜欢
随机推荐
Vulnhub靶机:GEMINI INC_ 2
ES6 advanced string processing new features
flink The object probably contains or references non serializable fields.
增加对 Textbundle 的支持
夫妻一方婚内向异性大额转款,怎么判
Traversal of DOM tree-----modify styles, select elements, create and delete nodes
调试技巧总结
The ifconfig compared with IP command
BUU brushing record
Detailed explanation of new features of ES advanced array function syntax
OpenCV创始人:开源绝不能完全免费!
Detailed explanation of new features of ES advanced function syntax
维特智能惯导配置
关于地图GIS开发事项的一次实践整理(上)
shell脚本入门
①In-depth analysis of CAS SSO single sign-on framework source code
Economic Misunderstandings in the Crypto World: Is Cash a Savings?Scarcity creates value?
【LeetCode】Day112-重复的DNA序列
The problem that Merge will be lost again after code Revert has been solved
Docker 链接sqlserver时出现en-us is an invalid culture错误解决方案
![[BX]和loop](/img/3c/1be08db6898613c3a1c0bcd39e73be.png)








