06 数据结构与算法之单链表面试题

标题单链表面试题:

  • 获取单链表有效节点个数:
public int getLength(HeroNode head){
	HeroNode temp = head;
	int length = 0;
	while(temp.next != null){
		length++;
		temp = temp.next;
	}
	return length;
}
  • 查找单链表中倒数第k个节点:
    把链表从头到尾遍历一遍,获取链表总长度len;
    再遍历一遍,第len-k+1个节点就是所需节点
public HeroNode findLastNode(HeroNode head, int k){
   if(head.next == null) return null;
   int len = getLength(head);
   if(k < 0 || k > len) return null;
   int count = 0;
   HeroNode temp = head;
   while(temp.next != null){
   	count++;
   	temp = temp.next;
   	if(count == len - k + 1) break;	
   }
   return temp;
}
  • 单链表的反转:
    遍历链表,将节点重新插入到头节点的后面。
public void reverseLinkedList(HeroNode head){
	if(head.next == null || head.next.next == null) return ;
	HeroNode cur = head.next;
    HeroNode next = null;
    head.next = null;
    while(cur != null){
    	next = cur.next;
        cur.next = head.next;
        head.next = cur;
        cur = next;
    }
}
  • 逆序打印单链表
    思路1:先将单链表进行反转操作,然后再遍历即可。这样做的问题是会破坏原来的单链表的结构,不建议
    思路2:利用栈这个数据结构,将各个数据节点压入栈中,然后利用栈的先进先出的特点来实现逆序打印
public void printFromLast(HeroNode head){
	if(head.next == null) return ;
    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());
    }
}
  • 合并两个单链表,合并之后依然有序
public HeroNode merge(HeroNode head1, HeroNode head2){
	HeroNode result = head1;
    if(head2.next == null) return result;
    HeroNode cur = head2.next;
    HeroNode next = null;
    while(cur != null){
    	next = cur.next;
    	HeroNode temp = result;
        while(temp.next != null && cur.no > temp.next.no){
        	temp = temp.next;
      	}
        if(temp.next != null && temp.next.no == cur.no){
        	System.out.println("编号重复了哦~");
     	}else{
        	cur.next = temp.next;
            temp.next = cur;
        }
        cur = next;
   }
   return result;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值