Java 找到单链表倒数第k个元素

mac2022-06-30  104

package List.www.cn;

import java.util.ArrayList;

/** * 在单链表中找打倒数第k个元素 * @author Administrator * */public class P236 { public static void main(String[] args) { int[] a= {1,2,3,4,5,6,7,8}; Node head=arr(a); int k=4; int head1=search(head,k); System.out.print(head1); } public static int search(Node head,int k) { if(head==null||k==0) return 0; Node next=head; Node cur=head; while(next!=null&&k>1) { cur=cur.next; k--; } while(cur!=null) { next=next.next; cur=cur.next; } return next.val; } public static Node arr(int[] a) { Node dummy=new Node(0); Node head=dummy; for(int i=0;i<a.length;i++) { Node cur=new Node(a[i]); dummy.next=cur; dummy=dummy.next; } return head.next; }

}

转载于:https://www.cnblogs.com/sgbe/p/10717861.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)