算法 - 链表操做思想 && case

算法 - 链表操做题目套路 前面这一篇文章主要讲链表操做时候的实操解决方式,本文从本质讲解链表操做的元信息,学完后,不再怕链表操做题目了。算法

1.链表的基本操做

链表的基本操做无外乎插入,删除,遍历大数据

插入的化,要考虑到前驱节点和后继节点,记住下面的伪代码人工智能

nex = 当前节点.next
当前节点.next = 插入的指针
插入指针.next = tmp

对于删除,是否会以为须要备份一下next的指针,答案是不用,执行语句是先取右边的值存起来而后赋值给左边的,因此直接下面一句话便可指针

cur.next = cur.next.next

对于遍历,其实是又迭代和递归的,另外又有前序和后序code

cur =  head
while cur != null {
   print(cur)
   cur = cur.next
}

//前序
dfs(cur) {
    if cur == null return
    print(cur.val)
    return dfs(cur.next)
}

2.链表的考点

链表的考点就只有对指针的修改和对指针的拼接,其中都须要对指针的前驱节点和后继节点进行保留,若是头节点不能首次肯定,或者可能会改变,那么又须要一个虚拟头节点,链表的考点无外乎就这些。递归

下面咱们来看两个题leetcode

删除链表中的重复元素rem

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/get

public ListNode deleteDuplicates(ListNode head) {
    //递归版
        if (head == null || head.next == null) 
            return head;
        
        if (head.val == head.next.val) {
            while (head.next != null && head.next.val == head.val) 
                head = head.next;
            head = deleteDuplicates(head.next);
        } else {
            head.next = deleteDuplicates(head.next);
        }

        return head;
}

判断是否为回文链表class

https://leetcode-cn.com/problems/palindrome-linked-list/

public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null)return true;
        temp = head;
        return dfs(head);
}

public boolean dfs(ListNode head){
    if(head == null)return true;
    boolean res = dfs(head.next) && temp.val == head.val;
    temp = temp.next;
    return res;
}

总结,链表的题目,掌握号指针的操做,就会简单点了,对于递归写法也会简化不少代码
吴邪,小三爷,混迹于后台,大数据,人工智能领域的小菜鸟。
更多请关注
file

相关文章
相关标签/搜索