Lintcode删除链表中倒数第n个节点

来源:互联网 发布:java 免费开源框架 编辑:程序博客网 时间:2024/06/06 00:16

删除链表中倒数第n个节点 

给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。


 注意事项

链表中的节点个数大于等于n

样例

给出链表1->2->3->4->5->null和 n = 2.

删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.


public class Solution {
    /*
     * @param head: The first node of linked list.
     * @param n: An integer
     * @return: The head of linked list.
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // write your code here
        if(head==null){
            return null;
        }
        ListNode a=head;//记录头节点用于遍历链表
        ListNode c=a;   //记录头结点由于返回删除后的链表
        int count=1;
        while(head!=null){     
            head=head.next;
            count++;           //计算出有多少节点
        }
        int b=count-n;      //所要删除的是第b个节点
        if(b==1){                   //删除第一个节点
            return c.next;
        }
        while(b!=0){
            a=a.next;
            b--;
            if(b==2){              //找到所要删除的节点的前一个位置
                a.next=a.next.next;
                break;
            }
        }
        return c;
    }
}

原创粉丝点击