22链表中倒数第K个节点

package sort;

class ListNode {
    int date;
    ListNode next;

    public ListNode(int date) {
        this.date = date;
    }

    public ListNode(int date, ListNode next) {
        // TODO Auto-generated constructor stub
        this.date = date;
        this.next = next;
    }

}

public class Test22 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1, null);
        ListNode temp = head;
        for (int i = 2; i <= 100; i++) {
            temp.next = new ListNode(i, null);
            temp = temp.next;

        }
        ListNode res = getback10(head, 1);
        System.out.println(res.date);

    }
     //真题思路是让前面的指针先走n步,然后两指针同时向前移动,当前面的指针指向null时,后面指针所指就是结果
    private static ListNode getback10(ListNode head, int i) {
        // TODO Auto-generated method stub
        ListNode tt = head;
        ListNode result = null;
        for (int j = 0; j < i; j++) {//前面的指针先走i步,
            if (tt != null)
                tt = tt.next;
            else
                return result;
        }
        result = head;

        while (tt != null) { //两指针同时移动直到前面指针所指为null
            tt = tt.next;
            result = result.next;

        }

        return result;
    }

}
 

发布了41 篇原创文章 · 获赞 1 · 访问量 771

猜你喜欢

转载自blog.csdn.net/coder_my_lover/article/details/105238207
今日推荐