밑에서 k번째 노드를 찾아서 돌아오기

1251 단어 LinkedList
마지막 k번째 노드를 찾아 반환: 코드 첨부:
package linkedlist;

import javax.swing.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * Created by Administrator on 2015/11/6 0006.
 */
public class Hashuan {
    public static void main(String[] args) {
        Node h1=new Node(0);
        Node head1=h1;
        Node t1=new Node(1);
        Node t2=new Node(2);
        Node t3=new Node(3);
        Node t4=new Node(4);
        head1.next=t1;
        t1.next=t2;
        t2.next=t3;
        t3.next=t4;
        t4.next=null;

        //System.out.println(panduan(head1));
        int k=2;
        System.out.println(daoshuK(head1,2).value);

    }

    private static Node daoshuK(Node head1,int k) {
        if(head1==null)
            return null;
        Node p=head1;
        Node q=head1;
        while (k>0){
            p=p.next;
            if(p==null)
                return null;
            k--;
        }
        while (p!=null){
            p=p.next;
            q=q.next;
        }
        return q;

    }
    static class Node{
        Node next;
        int value;

        public Node(int value) {
            this.value = value;
            next=null;
        }
    }
}

좋은 웹페이지 즐겨찾기