7、删除单链表倒数第n个节点

步骤
  • 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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值