单链表的一些题目,面试题

获取单链表的节点个数(如果是带头节点的链表,需求不统计头节点)

/**
	 * 
	 * @MethodName: 获取单链表的节点个数(如果是带头节点的链表,需求不统计头节点)
	 * @Description: TODO
	 * @author 63417
	 * @param head 链表的头节点
	 * @return 返回有效节点的个数
	 * @date 2021年1月9日
	 */
	public static int getLength(Node head) {
		if(head.next == null) { //空链表
			return 0;
		}
		int length = 0; //定义一个辅助变量
		Node cur = head.next; //这里没有统计头节点
		while(cur != null) {
			length++;
			cur = cur.next; //遍历
		}
		return length;
	}

查找单链表的倒数第k个节点

//1编写一个方法,接收head节点,同时接收一个index
//2 index表示是倒数第index个节点
//3 先把链表从头到尾遍历,得到链表的总的长度 getLength
//4 得到size后,从链表的第一个开始遍历(index - index)个
//5 如果找到了则返回该节点,否则返回null
public static Node findLastIndexNode(Node head, int index) {
		//判断链表是否为空
		if(head.next == null) {
			return null;
		}
		//第一次遍历得到链表的长度(节点个数)
		int size = getLength(head);
		//第二次遍历 size - index 位置,就是倒数的第k个节点
		//先做一个index的验证
		if(index <= 0 || index > size) {
			return null;
		}
		Node cur = head.next; //辅助指针
		for(int i = 0; i < size - index; i++) {
			cur = cur.next;
		}
		return cur;
	}

单链表的反转

/**
* 1、先定义一个节点reverseHead = new Node();
* 2、从头到尾遍历原来的链表,每遍历一个节点,就将其取出,并放置新的链表的最前端
* 3、原来的链表的head.next = reverseHead.next
*/

public static void reversList(Node head) {
		//如果当前链表为null,或者只有一个节点,则无需反转,直接返回
		if(head.next == null || head.next.next == null) {
			return;
		}
		Node cur = head.next; //辅助指针
		Node next = null; //指向当前节点【cur】的下一个节点
		Node reverseHead = new Node(0, "","");
		//遍历原来的链表
		while(cur != null) {
			next = cur.next; //临时保存当前节点的下一个节点
			cur.next = reverseHead.next; //将cur的下一个节点指向新的链表的最前端
			reverseHead.next = cur; //将cur连接到新的链表上
			cur = next; //让cur后移
		}
		//将head.next 指向reversHead.next,实现链表的反转
		head.next = reverseHead.next;
	}

从尾到头打印单链表

public static void reversePrint(Node head){
		if(head.next == null) {
			return;
		}
		//创建一个栈,将各个节点压入栈
		Stack<Node> stack = new Stack<>();
		Node cur = head.next;
		//将链表的所有节点压入栈
		while(cur != null) {
			stack.push(cur);
			cur = cur.next; //cur后移,压入下一个节点
		}
		//将栈中的节点进行打印,pop出栈
		while(stack.size() > 0) {
			System.out.println(stack.pop()); 
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值