算法 - 链表操作题目套路 后面这一篇文章次要讲链表操作时候的实操解决形式,本文从实质解说链表操作的元信息,学完后,再也不怕链表操作题目了。
1.链表的基本操作
链表的基本操作无外乎插入,删除,遍历
插入的化,要思考到前驱节点和后继节点,记住上面的伪代码
nex = 以后节点.next以后节点.next = 插入的指针插入指针.next = tmp
对于删除,是否会感觉须要备份一下next的指针,答案是不必,执行语句是先取左边的值存起来而后赋值给右边的,所以间接上面一句话即可
cur.next = cur.next.next
对于遍历,实际上是又迭代和递归的,另外又有前序和后序
cur = headwhile cur != null { print(cur) cur = cur.next}//前序dfs(cur) { if cur == null return print(cur.val) return dfs(cur.next)}
2.链表的考点
链表的考点就只有对指针的批改和对指针的拼接,其中都须要对指针的前驱节点和后继节点进行保留,如果头节点不能首次确定,或者可能会扭转,那么又须要一个虚构头节点,链表的考点无外乎就这些。
上面咱们来看两个题
删除链表中的反复元素
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
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;}
判断是否为回文链表
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;}
总结,链表的题目,把握号指针的操作,就会简略点了,对于递归写法也会简化很多代码
吴邪,小三爷,混迹于后盾,大数据,人工智能畛域的小菜鸟。
更多请关注