lc019

package
v0.0.0-...-b071cee Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2023 License: GPL-3.0 Imports: 2 Imported by: 0

README

19.删除链表的倒数第 N 个结点

1. 题目描述

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

示例 1:


输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]

示例 2:


输入:head = [1], n = 1
输出:[]

示例 3:


输入:head = [1,2], n = 1
输出:[1]

提示:

  • 链表中结点的数目为 sz
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

进阶: 你能尝试使用一趟扫描实现吗?

标签 链表 双指针

2. 解题

对链表的删除操作可以在头结点前加一个哑结点,减少删除时对头结点的判断。 1.两次遍历链表,第一次遍历得到链表的长度len,当遍历到第len−n+1 个节点时,就是我们需要删除的节点。 2.采用双指针遍历,先让快指针走n步,再让慢指针和快指针一起遍历,直到快指针遍历到链表最后一个结点,此时慢指针所指的位置即要删除的结点。

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ListNode

type ListNode struct {
	Val  int
	Next *ListNode
}

func BuildCircleListWithNoHead

func BuildCircleListWithNoHead(list []int, cursor int) *ListNode

BuildCircleListWithNoHead build a circle list, which tail point to list[cursor]

func BuildListWithHead

func BuildListWithHead(data []int) *ListNode

func BuildListWithNoHead

func BuildListWithNoHead(nums []int) *ListNode

func (*ListNode) HasCycle

func (l *ListNode) HasCycle() (bool, *ListNode)

HasCycle check if linklist has cycle structure, if not, return false, nil, if yes, return true and the cycle start node

func (*ListNode) Index

func (l *ListNode) Index(target int) *ListNode

Index return the node which value equals target

func (*ListNode) Len

func (l *ListNode) Len() int

Len return list length, when list has cycle structure, return -1

func (*ListNode) Slice

func (l *ListNode) Slice() []int

Slice return slice which contains all node's values in order.

func (*ListNode) String

func (l *ListNode) String() string

String implements Stringer interface.

func (*ListNode) Tail

func (l *ListNode) Tail() *ListNode

Tail return last list node

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL