华为OJ 初级:输出单向链表中倒数第k个结点

来源:互联网 发布:淘宝怎么修改发货单号 编辑:程序博客网 时间:2024/06/05 15:01

描述

输入一个单向链表,输出该链表中倒数第k个结点,链表的倒数第0个结点为链表的尾指针。

链表结点定义如下:

struct ListNode

{

      int       m_nKey;

      ListNode* m_pNext;

};

详细描述:

接口说明

原型:

ListNode* FindKthToTail(ListNode* pListHead, unsignedint k);

输入参数:

        ListNode* pListHead  单向链表

     unsigned int k  倒数第k个结点

输出参数(指针指向的内存区域保证有效):

    无

返回值:

        正常返回倒数第k个结点指针,异常返回空指针

 

 

知识点链表,查找,指针运行时间限制10M内存限制128输入

输入说明
1 输入链表结点个数
2 输入链表的值
3 输入k的值

输出

输出一个整数

样例输入8 1 2 3 4 5 6 7 8 4样例输出4
/*使用链表的方法,先定义一个节点,然后创建一个链表 * */import java.util.Scanner;public class Main{public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();TestList list = new TestList();for (int i = 0; i < n; i++)list.add(sc.nextInt());int k = sc.nextInt();sc.close();System.out.println(getNode(list, k));}private static int getNode(TestList list, int k) {Node second = list.head;if (k == 0 || list.head == null)return 0;int size = list.length() - k;for (int i = 1; i < size; i++) {second = second.next;if (second == null)return 0;}return second.data;}}class TestList {Node head = null;Node current = null;public void add(int data) {if (null == head) {head = new Node(data);current = head;} else {current.next = new Node(data);current = current.next;}}public int length() {int size = 0;if (null == head)return 0;current = head;while (current != null) {size++;current = current.next;}return size;}}class Node {int data;Node next;public Node(int data) {this.data = data;}}



0 0
原创粉丝点击