删除链表的倒数第n个结点

 

class Hero1 {
    public static void main(String[] args) {
        So7 sd0 = new So7(1);
        So7 sd1 = new So7(2);
        So7 sd2 = new So7(3);
        So7 sd3 = new So7(4);
        So7 sd4 = new So7(5);
        Solution solution = new Solution();
        solution.add(sd0);
        solution.add(sd1);
        solution.add(sd2);
        solution.add(sd3);
        solution.add(sd4);
        solution.remove(2);
        solution.list();
    }
}
class So7 {
    int val;
    So7 next;
    So7(){};
    So7(int val){
        this.val = val;
    }
    So7(int val,So7 next){
        this.val = val;
        this.next = next;
    }
}
class Solution{
    private So7 head = new So7(0);
    public void add(So7 node){
    So7 temp = head;
    while(true){
        if (temp.next==null){
            break;
        }
        temp = temp.next;
    }
    temp.next = node;
    }
    public So7 remove(int n){
        So7 dummy = new So7(0,head);
        int length = getLength(head);
        So7 cur = dummy;
        for (int i = 0; i < length-n; i++) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
       So7 ans = dummy.next;
        return ans;
    }
    public int getLength(So7 head){
        int length = 0;
        while(head != null){
            ++length;
            head = head.next;
        }
        return length;
    }
    public void list(){
        if(head.next == null){
            return;
        }
        So7 temp = head.next;
        while (true){
            if(temp == null){
                break;
            }
            System.out.println(temp.val);
            temp = temp.next;
        }
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值