链表

链表是最基本的数据结构959370442,面试官也常常用链表来考察面试者的基本能力,而且链表相关的操作相对而言比较简单,也适合考察写代码的能力。链表的操作也离不开指针,指针又很容易导致出错。

public class ListNode {
     int val;
     ListNode next;
     ListNode(int x) {
         val = x;
         next = null;
    }
}

删除节点

思路:
  • 下一个节点复制到当前
public void deleteNode(ListNode node) {
    if (node.next == null){
        node = null;
        return;
    }
    // 取缔下一节点
    node.val = node.next.val
    node.next = node.next.next
}

翻转链表

思路

思路:每次都将原第一个结点之后的那个结点放在新的表头后面。
比如1,2,3,4,5

  • 第一次:把第一个结点1后边的结点2放到新表头后面,变成2,1,3,4,5
  • 第二次:把第一个结点1后边的结点3放到新表头后面,变成3,2,1,4,5
  • ……
  • 直到: 第一个结点1,后边没有结点为止。
视频

大圣算法 翻转链表(Reverse Linked List ) -- LeetCode 206

public ListNode reverse(ListNode head) {
    //prev表示前继节点
    ListNode prev = null;
    while (head != null) {
        //temp记录下一个节点,head是当前节点
        ListNode temp = head.next;
        head.next = prev;
        prev = head;
        head = temp;
    }
    return prev;
}

中间元素

思路

我总结了一下,可以称为 田忌赛马’

public ListNode findMiddle(ListNode head){
    if(head == null){
        return null;
    }

    ListNode slow = head;
    ListNode fast = head;

    // fast.next = null 表示 fast 是链表的尾节点
    while(fast != null && fast.next != null){
        fast = fast.next.next;
        slow = slow.next;
    }
    return slow;
}

合并两个已排序链表

思路
  • 递归方法:首先比较给新链表接上一个结点,然后这个结点的next就是剩下的两条链表合并的结果。
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode lastNode = dummy;

    while (l1 != null && l2 != null) {
        if (l1.val < l2.val) {
            lastNode.next = l1;
            l1 = l1.next;
        } else {
            lastNode.next = l2;
            l2 = l2.next;
        }
        lastNode = lastNode.next;
    }

    if (l1 != null) {
        lastNode.next = l1;
    } else {
        lastNode.next = l2;
    }

    return dummy.next;
}
01-20 03:36
查看更多