链表类常见算法题总结
Posted sshhsun-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表类常见算法题总结相关的知识,希望对你有一定的参考价值。
链表类常见算法题目总结
1.反转链表
翻转思想:
代码实现:
public class SinglyLinkedList_reverse
public static <T> void reverse(MSinglyLinkedList<T> list)
Node<T> p = list.head.next, succ = null, front = null;
while (p != null)
succ = p.next;//保存p的后继节点
p.next = front;//使得p.next指向其前驱front
front = p;
p = succ;
list.head.next = front;
public static void main(String[] args)
String[] values = "A", "B", "C", "D", "E", "F" ;
MSinglyLinkedList<String> list = new MSinglyLinkedList<String>(values);
System.out.println("翻转前" + list.toString());
reverse(list);
System.out.println("翻转后" + list.toString());
2.给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。
样例
给出链表1->2->3->4->5->null和 n = 2.删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode removeNthFromEnd(ListNode head, int n)
if (n <= 0)
return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode preDelete = dummy;
for (int i = 0; i < n; i++)
if (head == null)
return null;
head = head.next;
while (head != null)
head = head.next;
preDelete = preDelete.next;
preDelete.next = preDelete.next.next;
return dummy.next;
以上是关于链表类常见算法题总结的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode练习(Python):链表类:第23题:合并K个排序链表:合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。