题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;

//struct ListNode // { // int m_nKey; // ListNode* m_pNext; // }; public class Main{ public static void main(String[]args)throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String str = null; while((str = in.readLine()) != null){ int num = Integer.parseInt(str); String[] s = in.readLine().split(" "); int[] arr = new int[s.length]; for(int i = 0;i < s.length;i ++ ){ arr[i] = Integer.parseInt(s[i]); } ListNode head = createList(arr); int k = Integer.parseInt(in.readLine()); if(k <= 0){ System.out.println(0); continue; } ListNode pre = head; ListNode post = head; while(k -- > 0 && pre != null){ pre = pre.next; } while(pre != null){ pre = pre.next; post = post.next; } System.out.println(post.key);

    }

}
public static ListNode createList(int[] arr){
    ListNode head = new ListNode();
    ListNode tail = head;
    for(int i = 0;i < arr.length;i++){
        ListNode temp = new ListNode();
        temp.key = arr[i];
        temp.next = null;
        tail.next = temp;
        tail = temp;
    }
    return head;
}
public static class ListNode{
    int key;
    ListNode next;

    public int getKey() {
        return key;
    }

    public void setKey(int key) {
        this.key = key;
    }

    public ListNode getNext() {
        return next;
    }

    public void setNext(ListNode next) {
        this.next = next;
    }
}

}

我居南半坡 文章被收录于专栏

多刷题,积蓄力量,欢迎讨论

全部评论

相关推荐

渴望wlb的牛油果很...:直说卡第一学历不就行了 非得拐弯抹角
点赞 评论 收藏
分享
10-09 17:17
已编辑
门头沟学院 Java
活泼的代码渣渣在泡池...:同学你好,我也是学院本,后天要面这个亚信科技,是实习,请问问题都啥样呀,我项目就做了网上的,这是第一次面试
投递多益网络等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务