单链表练习题

求单链表中有效节点的个数

	/**
	 * 获取单链表中的有效个数不计算头结点
	 */
	public static int getlength(HeroNode head) {
		if (head == null) {
			System.out.println("空链表");
		}
		int length=0;
		HeroNode cur=head.next;
		while (cur != null) {
			length++;
			cur = cur.next;
		}
		return length;
	}

找单链表中的倒数第k个结

/**
	 * 查找单链表中的倒数第k个结点
	 * index表示倒数第index个节点
	 * 首先遍历整个链表得到总长度lenth
	 * (lenth-index)就是要找的位置
	 */
	public static HeroNode find(HeroNode head,int index) {
		if (head.next== null) {
			System.out.println("链表为空");
		}
		int length = getlength(head);
		if (index<=0||index > length) {
			System.out.println("该节点不存在");
		}
		//辅助变量
		HeroNode cur = head.next;
		for (int i = 0; i < length-index; i++) {
			cur = cur.next;
		}
		return cur;
	}

链表的反转,反转会破坏原来的链表结构

/**
	 * 反转单链表
	 * 遍历原链表,每遍历一次就取出一个放在新链表的最前端
	 */
	public static void revers(HeroNode head) {
		//链表为空或只有一个节点无需反转
		if (head.next == null||head.next.next == null) {
			return;
		}
		HeroNode cur=head.next;
		//该节点用于指向cur的下一个节点
		HeroNode next=null;
		HeroNode rhead=new HeroNode(0, "","");
		while(cur != null) {
			//临时保存
			next = cur.next;
			//将该节点取出放在新链表的最前端
			cur.next=rhead.next;
			//和头结点连起来
			rhead.next = cur;
			//后移
			cur=next;
		}
		//循环结束后链表内除头结点,其余都被反转保存到了新链表中
		head.next = rhead.next;
	}

尾到头打印单链

	/**
	 * 利用栈的先进后出特性实现逆序打印链表
	 */
	public static void reversP(HeroNode head) {
		if (head.next == null ) {
			System.out.println("空链表");
		}
		//创建一个栈
		Stack<HeroNode> stack = new Stack<HeroNode>();
		//辅助节点
		HeroNode cur=head.next;
		//将所有节点压入栈
		while (cur != null) {
			stack.push(cur);
			cur = cur.next;
		}
		//出栈
		while (stack.size() > 0) {
			System.out.println(stack.pop());
		}
	}

合并两个有序的链表

首先初始化一个链表用于保存结果,然后让cur指向它

定义两个新链表指向原来的两个链表,避免改变原链表内的结构

循环合并:当List1或List2为空时(到达尾部的时候)跳出循环

 对List1的数据域和List2的数据域循环比较,将较小的放入链表中,然后链表后移,较小的那一个也后移

结束循环后有两种情况,List1为空或List2为空

1 若List1不为空,就把List1接到链表尾部

2 反之,就把List2接到链表尾部

返回合并后链表

public  static Single merge(Single List1,Single List2) {
		//保存合并后的链表
		Single res = new Single();
		Node cur = res.head;
		//接收第一个链表
		Single Lista=List1;
		Node a=Lista.head.next;
		//接收第二个链表
		Single Listb=List2;
		Node b=Listb.head.next;
		//合并
		while(a!=null&&b!=null) {
			if (a.no<=b.no) {
				cur.next=a;
				cur=cur.next;
				a=a.next;
			}else {
				cur.next=b;
				cur=cur.next;
				b=b.next;
			}
		}
		cur.next = a==null ? b : a;
		return res;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1while(true){learn}

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值