2021-02-09:如何删除一个链表的倒数第n个元素?

2021-02-09:如何删除一个链表的倒数第n个元素?

福哥答案2021-02-09:

1.创建虚拟头元素,虚拟头元素的Next指针指向头元素。
2.根据快慢指针求倒数第n+1个元素,假设这个元素是slow。
3.设置元素slow的Next指针。slow.Next=slow.Next.Next。
4.返回虚拟头元素的Next指针。

代码用golang编写,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
 
import "fmt"
 
type ListNode struct {
    Val  int
    Next *ListNode
}
 
func main() {
    head := &ListNode{}
    head.Val = 1
 
    head.Next = &ListNode{}
    head.Next.Val = 2
 
    head.Next.Next = &ListNode{}
    head.Next.Next.Val = 3
 
    head.Next.Next.Next = &ListNode{}
    head.Next.Next.Next.Val = 4
 
    ret := head
    for ret != nil {
        fmt.Print(ret.Val, " ")
        ret = ret.Next
    }
 
    fmt.Println("\r\n-------")
    k := 4
    fmt.Println("删除倒数第", k, "个元素后:")
 
    ret = DeleteNode(head, k)
    for ret != nil {
        fmt.Print(ret.Val, " ")
        ret = ret.Next
    }
}
func DeleteNode(head *ListNode, k int) *ListNode {
    preHead := &ListNode{}
    preHead.Next = head
 
    fast := preHead
    slow := preHead
 
    k++
    for k > 0 {
        fast = fast.Next
        k--
    }
 
    for fast != nil {
        fast = fast.Next
        slow = slow.Next
    }
 
    slow.Next = slow.Next.Next
 
    return preHead.Next
}

  

执行结果如下:

 

 


***
[评论](https://user.qzone.qq.com/3182319461/blog/1612827291)

posted @   福大大架构师每日一题  阅读(88)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示