有关单链表的两个问题【遍历一次求中间节点,倒数第K个结点】

package com.zhiru;

/*
 * 一个无附加头结点的单向链表示例
 */
public class LinkedList<T> {
	private Node head;
	private Node cur;
	private int len;// 链表长度。

	private class Node {
		public T val;
		public Node next;

		Node(T v) {
			val = v;
			next = null;
		}
	}

	public LinkedList() {
		head = cur = null;
		len = 0;
	}

	public int getLen() {
		return len;
	}
	//后插法建立单向单链表
	public void insert(T[] a) {
		if (a == null)
			return;
		int i = 0;
		len = a.length;
		head = cur = new Node(a[i]);
		head.next = cur;
		while (i < a.length - 1) {
			Node p = new Node(a[++i]);
			cur.next = p;
			cur = p;
		}
	}

	public void prtList() {
		if (head == null)
			return;
		Node t = head;
		while (t != null) {
			System.out.print(t.val + " ");
			t = t.next;
		}
		System.out.print("\n");
	}

	/*
	 * 查找链表的中间节点 定义两个指针p1,p2, 同时从头开始,p1一次走一步,p2一次走两步 当p2到链尾时,p1就走到了中间
	 */
	public void findMidVal() {
		Node p1, p2;
		Node p;
		p1 = p2 = head;
		while (p2.next.next != null) {
			if (p2.next != null) {
				p1 = p1.next;
				p2 = p2.next.next;
			} else {
				p = p1.next;
				break;
			}
		}
		p=p1;
		System.out.println("链表中间节点值为:" + p.val);

	}

	/*
	 * 找到链表的倒数第k各节点 即找到顺数第len-k+1个结点 只遍历一次就找到倒数第k个节点
	 */
	public void findKthNode(int k) {
		if (k <= 0 || head == null)
			return;
		Node p = head;
		Node p1 = head;
		// p先走k-1步
		for (int i = 1; i <= k - 1; i++)
			p = p.next;
		// 然后p2在走
		while (p.next != null) {
			p = p.next;
			p1 = p1.next;
		}
		System.out.println("链表倒数第" + k + "个结点值为:" + p1.val);
	}
}

public static void main(String[] args) {
		Integer[]b={0,2,4,67,8,9,11,22,33,44};
		LinkedList<Integer> list=new LinkedList<Integer>();
		list.insert(b);
		list.prtList();
		list.findMidVal();
		list.findKthNode(7);
	}

0 2 4 67 8 9 11 22 33 44 
链表中间节点值为:8
链表倒数第7个结点值为:67



参考博客:http://blog.csdn.net/jungsagacity/article/details/7356201

参考书籍:<<剑指offer>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值