删除链表倒数k个节点

这个题 并没有用两个链表分步走,使用另外一种方法,
首先遍历链表,并k--;如果k最后等于0,则链表的倒数第k个节点就是链表头结点,直接返回head.next
若k<0,则链表的长度比k大,现在k的值等于k-n,将链表从head再从头走,k++;当k=0时,链表就停在n-k个节点,就是倒数第k个节点
的前一个节点

/**
 * Created by 糖糖 on 2017/8/2.
 */
public class removeLastKnode {
    public static  node  remove(node head,int k){
        if(head==null||k<-1){
            return head;
        }
        node cur=head;
        while (cur!=null){
            cur=cur.next;
            k--;
        }
        if(k==0)
            return head.next;
        if(k<0){
            cur = head;
            while (++k!=0){
                cur=cur.next;
               // k++;
            }
            cur.next=cur.next.next;
        }
        return head;
    }
    public static  void  main(String args[]){
        node n1=new node(2);
        node n2=new node(5);
        node n3=new node(6);
        node n4=new node(7);
        n1.next=n2;
        n2.next=n3;
        n3.next=n4;
        node n5=new node(12);
        node n6=new node(16);
        node n7=new node(17);
        n4.next=n5;
        n5.next=n6;
        n6.next=n7;
       node result = remove(n1,3);
        while (result!=null) {
            System.out.print(result.data+ " ");
            result = result.next;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值