
package com.itheima.test;
class Solution {
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
head.next.next.next.next.next = new ListNode(6);
//head.next.next.next.next.next.next.next= new ListNode(7);
//head.next.next.next.next.next.next.next.next= new ListNode(8);
//head.next.next.next.next.next.next.next.next.next= new ListNode(9);
printLinkedList(deleteNode(10,head));
}
public static void printLinkedList(ListNode head) {
System.out.print("Linked List: ");
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
public static ListNode deleteNode(int index,ListNode head){
if (index<0||index>length(head)) {
System.out.println("没有找到该节点");
}
if(index == 1){//删除头结点
head = head.next;
return head;
}
ListNode preNode = head;
ListNode curNode = preNode.next;
int i = 2;
while(curNode != null){
if(i==index){//寻找到待删除结点
preNode.next = curNode.next;//待删除结点的前结点指向待删除结点的后结点
}
//当先结点和前结点同时向后移
preNode = preNode.next;
curNode = curNode.next;
i++;
}
return head;
}
private static int length(ListNode head) {
int length=0;
while (head!=null){
length++;
head=head.next;
}
return length;
}
}
近期评论