链表节点删除

 

 

代码:

 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 @ 2022-08-29 20:30  yky_xukai的胡思乱想  阅读(25)  评论(0)    收藏  举报