链表节点删除

 

 

代码:

复制代码
 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 }
复制代码

 

posted @   yky_xukai的胡思乱想  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
点击右上角即可分享
微信分享提示