剑指offer 15. 链表中倒数第k个结点

来源:互联网 发布:淘宝图书怎么样 编辑:程序博客网 时间:2024/06/05 19:41
class ListNode {int data;ListNode next;}// 题目:输入一个链表输出链表的倒数第k个结点// 解法:设置两个标记,先让第一个走k步,接着让他们同步移动,知道第一个到末尾,第二个则为倒数第二个结点public class Main {public static void main(String[] args) throws Exception {ListNode n1 = new ListNode();ListNode n2 = new ListNode();ListNode n3 = new ListNode();ListNode n4 = new ListNode();ListNode t1 = new ListNode();ListNode t2 = new ListNode();ListNode t3 = new ListNode();ListNode t4 = new ListNode();n1.data = 1;n2.data = 3;n3.data = 5;n4.data = 7;t1.data = 2;t2.data = 4;t3.data = 6;t4.data = 8;n1.next = n2;n2.next = n3;n3.next = n4;n4.next = t1;t1.next = t2;t2.next = t3;t3.next = t4;ListNode result = reverseList(n1,9);System.out.println(result.data);}public static ListNode reverseList(ListNode node,int k) throws Exception {if(node == null){return node;}ListNode pre = node;ListNode result = node;int temp = 1;while(temp<k){//先让pre结点走k步pre = pre.next;if(pre == null){//如果k大于链表长度,则直接返回throw new Exception("not found");}temp++;}while(pre.next!=null){//再让两个结点同时回退pre = pre.next;result = result.next;}return result;}}

0 0
原创粉丝点击