求单链表中倒数第k个结点

来源:互联网 发布:python黑客编程中文pdf 编辑:程序博客网 时间:2024/06/08 06:24

所实现链表为无头结点的单链表

两种方法:

public class LinkList {    public Node head;//头结点    public Node current;    /*1.遍历法:即先遍历链表求出链表的长度n,然后第二次遍历求出倒数第k个结点,该方法容易想到,但是效率太低,可以进行优化*/    public Node findLastNode(int index){        if(head == null)//如果链表为空,则返回null            return null;        current = head;//current指向当前第一个结点        int size = 0;        /*遍历求得链表的长度size*/        while(current != null){            size++;            current = current.next;        }        /*对index进行判断,分为index<1和index超出链表长度两种情况*/        if(index<1||index>size)            return null;        current = head;        /*第二次遍历,求出倒数第k个结点*/        for(int i=0;i<size-index;i++)            current = current.next;        return current;    }    /*方法2:采用两个指针进行遍历,让第一个指针先前行k-1个结点,然后两个指针同时往后遍历,待到第一个指针指向最后一个结点时,第二个指针便指向了目标结点。时间复杂度为O(n).可采用画图法自己进行遍历,简单易懂*/    public Node findLastNode(Node head,int index){        /*先进行判断,链表为空或者index小于1时,返回null*/        if(head == null || index <1)             return null;        /*定义两个指针*/        Node first = head;        Node second = head;        /*first指针先向前移动k-1个位置,此时first与second相差k-1*/        for(int i=0;i<index-1;i++){            first = first.next;            /*在first遍历过程中如果first指向了null,则代表index超出了链表的长度,则返回null*/            if(first == null)                return null;        }        /*first和second两个指针同时往后移动,等到first指向了最后一个结点即(first.next == null)时,遍历便结束*/         while(first.next != null){            first = first.next;            second = second.next;        }        return second;    }    class Node{        int data;//数据域        Node next;//指针域        public Node(int data){            this.data  = data;        }    }
0 0
原创粉丝点击