java单链表面试题(腾讯、百度、新浪)

新浪----查找单链表中的倒数第K个节点
思路分析:遍历整个链表,得到链表的总长度size,接着再次遍历(size-k)个即可。

public static Node findNode(Node head,int k){
 if(head.next==null){
       return null;
    }
    int size=getLength(head);
    if(k<=0||k>size){
       return null;
      }
      //定义辅助变量cur
      ode cur=head.next;
      for(int i=0;i<size-k;i++){
      cur=cur.next;
      }
      return cur;
      }

腾讯—单链表的反转
思路分析:
思路:

  1. 先定义一个节点 reverseHead = new HeroNode();
  2. 遍历链表,每遍历一个节点,就将其取出,并放在新的链表reverseHead 的最前端.
  3. 原来的链表的head.next = reverseHead.next;
public static void reversetList(Node head){
     if(head.next==null||head.next.next==null){
      return;
      }
      Node cur=head.next;
      Node next=null;
      NOde reverseHead=new Node(0,"","");
      while(cur!=null){
      next=cur.next;//先暂时保存当前节点的下个节点
      cur.next=reverseHead.next;//将cur接到新的链表上
      cur=next;//后移
      }
      head.next=reverseHead.next;
     }

百度–从尾到头打印单链表
思路:将各个节点压入到栈中,然后利用栈的先进后出的特点,将节点逐个出栈

public static reversePrint(Node head){
  if(head.next==null){
    retur;
  }
  
   Stack<Node>stack=new Stack<Node>();
   Node cur=head.next;
   while(cur!=null){
      stack.push(cur);
      cur=cur.next;
   }
   while(stack.size()>0){
   System.out.println(stack.pop());
   }
 }
   
发布了32 篇原创文章 · 获赞 28 · 访问量 1323

猜你喜欢

转载自blog.csdn.net/weixin_42369886/article/details/104529481
今日推荐