算法:链表
Posted danfengw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:链表相关的知识,希望对你有一定的参考价值。
判断链表有环
思路:快慢指针
两链表合并
https://leetcode-cn.com/problems/add-two-numbers/
思路:
1、链表 head 记录初始链表,tempHead 记录当前点的链表
2、输入l1 与 l2 长度可能不一致
3、进位记录 carry
public static ListNode addTwoNumbers(ListNode l1, ListNode l2)
int carry = 0;
ListNode head = new ListNode();
ListNode tempHead = head;
head.next = tempHead;
while (l1 != null || l2 != null)
ListNode tempNode = new ListNode();
int l1val = l1 == null ? 0 : l1.val;
int l2val = l2 == null ? 0 : l2.val;
int result = l1val + l2val + carry;
carry = result / 10;
tempNode.val = result % 10;
tempHead.next = tempNode;
tempHead = tempHead.next;
if (l1 != null)
l1 = l1.next;
if (l2 != null)
l2 = l2.next;
if (carry > 0)
ListNode tail = new ListNode(carry);
tempHead.next = tail;
return head.next;
查找单链表中的倒数第k个结点
快慢指针
如何实现一个lru
前后结点
如何定位链表尾部前面的第k个节点,写一下
双指针
单链表的反转
方式一:
public ListNode reverseList(ListNode head)
if(head==null) return head;
if (head.next==null) return head;
ListNode lastNode = reverseList(head.next);
head.next.next = head;
head.next = null;
return lastNode;
方式二:
public ListNode reverseList(ListNode head)
if (head == null) return head;
ListNode tempHead = new ListNode(0);
ListNode tempNext = tempHead.next;
while (head != null)
ListNode curNext = head.next;
head.next = tempNext;
tempNext = head;
head = curNext;
return tempNext;
从尾到头打印单链表
思路: 使用栈
合并两个有序的单链表,合并之后的链表依然有序
public ListNode mergeTwoLists(ListNode l1, ListNode l2)
ListNode prehead = new ListNode(-1);
ListNode prev = prehead;
while (l1 != null && l2 != null)
if (l1.val <= l2.val)
prev.next = l1;
l1 = l1.next;
else
prev.next = l2;
l2 = l2.next;
prev = prev.next;
// 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
prev.next = l1 == null ? l2 : l1;
return prehead.next;
求单链表中有效节点的个数
以上是关于算法:链表的主要内容,如果未能解决你的问题,请参考以下文章