链表节点删除
代码:
1 import java.util.*; 2 3 public class Main{ 4 public static void main(String[] args){ 5 Scanner scan = new Scanner(System.in); 6 int m = scan.nextInt(); 7 int N = scan.nextInt(); 8 // 1.特殊情况全部删除 9 if(N == 1){ 10 return ; 11 } 12 // 2.构造链表 13 ListNode root = new ListNode(1); 14 ListNode curr = root; 15 for(int i=2;i<=m;i++){ 16 ListNode node = new ListNode(i); 17 curr.next = node; 18 curr = node; 19 } 20 // 3.删除链表 21 ListNode res = deleteN(root,m,N); 22 ListNode cu = res; 23 System.out.print(cu.value+" "); 24 while(cu.next!=null){ 25 cu = cu.next; 26 System.out.print(cu.value+" "); 27 } 28 } 29 30 public static ListNode deleteN(ListNode root,int m,int N){ 31 ListNode prev = null; 32 ListNode next = null; 33 ListNode curr = root; 34 for(int i=2;i<=m;i++){ 35 prev = curr; 36 curr = curr.next; 37 if(i%N == 0){ 38 // 删除节点 删除curr 39 prev.next = curr.next; 40 } 41 } 42 return root; 43 } 44 45 static class ListNode{ 46 int value; 47 ListNode next; 48 ListNode(){} 49 ListNode(int value){ 50 this.value = value; 51 } 52 } 53 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程