老规矩,官方代码:作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/ 来源:力扣(LeetCode)?
个人微改: import java.util.*; class ListNode{ ?? ?int val; ?? ?ListNode next; ?? ?ListNode() {} ?? ?ListNode(int val){this.val=val;} ?? ?ListNode(int val,ListNode next){this.val = val;this.next=next;} ?? ? ?? ?public void addNode(int e) { ?? ??? ?ListNode newNode = new ListNode(e); ?? ??? ?if(this.next==null) { ?? ??? ??? ?this.next = newNode; ?? ??? ?}else { ?? ??? ??? ?this.next.addNode(e); ?? ??? ?} ?? ?} ?? ? ?? ?public ListNode remove(ListNode head,int n) { ?? ??? ?ListNode rookie = new ListNode(0,head); ?? ??? ?int length = getLength(head); ?? ??? ?ListNode cur = rookie; ?? ??? ?for(int i=1;i<length-n+1;i++) { ?? ??? ??? ?cur = cur.next; ?? ??? ?} ?? ??? ?cur.next = cur.next.next; ?? ??? ?ListNode ans = rookie.next; ?? ??? ?return ans; ?? ?} ?? ?public int getLength(ListNode head) { ?? ??? ?int length = 0; ?? ??? ?while(head!=null) { ?? ??? ??? ?++length; ?? ??? ??? ?head = head.next; ?? ??? ?} ?? ??? ?return length; ?? ?} ?? ?public void print() { ?? ??? ?System.out.print(this.val); ?? ??? ?if(this.next!=null) { ?? ??? ??? ?System.out.print("-->"); ?? ??? ??? ?this.next.print(); ?? ??? ?} ?? ?} } public class deleteLinkList { ?? ?public static void main(String args[]) { ?? ??? ?ListNode L1 = new ListNode(); ?? ??? ?System.out.println("please enter the linked list capacity :"); ?? ??? ?Scanner sc = new Scanner(System.in); ?? ??? ?int m = sc.nextInt(); ?? ??? ?int a[] = new int[m]; ?? ??? ?System.out.println("please enter the data of your linked list :"); ?? ??? ?for(int i=0;i<m;i++) { ?? ??? ??? ?a[i]=sc.nextInt(); ?? ??? ??? ?L1.addNode(a[i]); ?? ??? ?} ?? ??? ?System.out.println("please enter the number of reciprocal of the list you want to delete :"); ?? ??? ?int n = sc.nextInt(); ?? ??? ?L1.remove(L1.next,n); ?? ??? ?L1.next.print(); ?? ??? ?sc.close(); ?? ??? ? ?? ?} } 测试结果:
please enter the linked list capacity : 5 please enter the data of your linked list : 1 2 3 4 5 please enter the number of reciprocal of the list you want to delete : 2 1-->2-->3-->5
|