题目描述
给定一个链表,实现删除链表第 K 个节点的函数。
输入描述:
n 表示链表的长度。
m 表示删除链表第几个节点。
val 表示链表节点的值。
输出描述:
在给定的函数中返回链表的头指针。
示例1
输入
5 3
1 2 3 4 5
输出
1 2 4 5
解法一:正常写就行
import java.io.*;
public class Main{
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static ListNode creat(int len,String[] ss){
ListNode head = new ListNode(0);
ListNode r = head;
for(int i=0;i<len;i++){
ListNode node = new ListNode(Integer.parseInt(ss[i]));
r.next = node;
r = node;
}
return head.next;
}
public static ListNode del(ListNode head,int index){
if(head==null) return head;
ListNode r = new ListNode(0);
r.next = head;
ListNode tmp = r;
while(tmp.next!=null){
index--;
if(index==0){
tmp.next = tmp.next.next;
break;
}
tmp = tmp.next;
}
return r.next;
}
public static void main(String[] args) throws IOException{
String[] s1 = br.readLine().trim().split(" ");
int len = Integer.parseInt(s1[0]);
int index = Integer.parseInt(s1[1]);
String[] ss = br.readLine().trim().split(" ");
ListNode head = creat(len,ss);
head = del(head,index);
StringBuilder sb = new StringBuilder();
while(head!=null){
sb.append(head.val).append(" ");
head = head.next;
}
System.out.print(sb.toString());
}
}
class ListNode{
int val;
ListNode next;
public ListNode(int val){
this.val = val;
this.next = next;
}
}
本文提供了一种在链表中删除指定位置节点的算法实现,通过创建链表、定义链表节点并实现删除函数,最后输出修改后的链表。示例代码使用Java编写,展示了从链表中删除第K个节点的具体过程。

1391

被折叠的 条评论
为什么被折叠?



