步骤
- 1、假设链表长度为len,删除倒数第n个节点,那么节点的正数位置为:pos = len-n+1
- 2、所以可以用快慢指针,快指针先走n步,然后快慢指针一起移动,直到快指针为null,那么此时,慢指针走的步数为:len-n+1,也就是要删除的节点位置:
public class DeleteOneNode {
private static Node head;
private static Node tail;
public static void main(String[] args) {
String[] array = {"1", "2", "3", "4", "5"};
for(int i = 0; i < array.length; i++) {
createLinkd(array[i]);
}
System.out.println("原链表");
printAll();
deleteNode(5);
}
public static void deleteNode(int pos) {
if(pos > 0) {
Node fast = head;
Node slow = head;
Node pre = null;
boolean flag = true;
for(int i = 0; i < pos; i++) {
if(fast == null) {
System.out.println("链表长度不够");
flag = false;
break;
} else {
fast = fast.next;
}
}
while(fast != null) {
pre = slow;
slow = slow.next;
fast = fast.next;
}
if(flag) {
if(slow == head) {
head = head.next;
} else {
pre.next = slow.next;
}
System.out.println("删除后链表为:");
printAll();
}
}
}
public static void createLinkd(String data) {
Node node = new Node(data);
if(head == null) {
head = node;
tail = node;
} else {
tail.next = node;
tail = node;
}
}
public static void printAll() {
Node cur = head;
while(cur != null) {
System.out.print(cur.data + "-->");
cur = cur.next;
}
System.out.println();
}
static class Node{
public Node next;
public String data;
private Node(String data) {
this.data = data;
}
}
}