4.算法笔记——链表

左神算法笔记
摘要由CSDN通过智能技术生成

面试时链表解题的方法论
  1)对于笔试,不用太在乎空间复杂度,一切为了时间复杂度
  2)对于面试,时间复杂度依然放在第一位,但是一定要找到空间最省的方法
重要技巧:
  1)额外数据结构记录(哈希表等)
  2)快慢指针

1.反转链表
  public calss ReverseList {
    public static class Node {
      public int value;
      public Node next;
      public Node(int data) {
        this.value = data;
      }
    }
    public static Node reverseList(Node head) {
      Node pre = null;
      Node next = null;
      while (head != null) {
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
      }
      return pre;
    }
    
    public static class DoubleNode {
      public int value;
      public DoubleNode last;
      public DoubleNode next;
      public DoubleNode(int data) {
        this.value = data;
      }
    }
    public static DoubleNode reverseList(DoubleNode head) {
      DoubleNode pre = null;
      DoubleNode next = null;
      while (head != null) {
        next = head.next;
        head.next = pre;
        head.last = next;
        pre = head;
        head = next;
      }
      return pre;
    }
  }
  
  

2.打印两个链表的有序部分
  public static void printCommonPart(Node head1, Node head2) {
    while (head1 != null && head2 != null) {
      if (head1.value < head2.value) {
        head1 = head1.next;
      } else if (head1.value > head2.value) {
        head2 = head2.next;
      } else {
        System.out.println(head1.value + " ");
        head1 = head1.next;
        head2 = head2.next;
      }
    }
  }

3.判断一个链表是不是回文链表
  方法一:(需要N的额外空间)
  遍历链表,然后将数据存入栈中,最后再遍历一次链表,比较是否与栈中数据相等
  public static boolean isP(Node head) {
    Stack<Node> stack = new Stack<>();
    Node cur = head;
    while (cur != null) {
      stack.push(cur);
      cur = cur.next;
    }
    while (head != null) {
      if (head.value != stack.pop().value) {
        return false;
      }
      head = head.next;
    } 
    return true;
  }
  
  方法二:(需要N/2的额外空间)
  使用快慢指针,快指针遍历到结尾时,慢指针刚好到达中间,然后再将慢指针后面的数存入栈中,再遍历N/2的链表即可
  public static boolean isP(Node head) {
    if (head == null || head.next == null) {

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值