小小程知识库 小小程知识库
首页
Golang
MySQL
归档
GitHub (opens new window)

xxcheng

记录美好生活~
首页
Golang
MySQL
归档
GitHub (opens new window)
  • 剑指offer记录

    • day02
    • day03
    • day04
    • day05
      • JZ76 删除链表中重复的结点
        • 我的实现
        • 官方思路
      • JZ18 删除链表的节点
    • day06
  • 算法
  • 剑指offer记录
xxcheng
2023-07-29
目录

day05

# JZ76 删除链表中重复的结点 (opens new window)

图片

# 我的实现

package main

import . "nc_tools"

/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * @param pHead ListNode类
 * @return ListNode类
 */
func deleteDuplication(pHead *ListNode) *ListNode {
	if pHead == nil {
		return nil
	}
	next := pHead.Next
	cur := pHead
	head := &ListNode{0, cur}
	prev := head
	for next != nil {
		if cur.Val == next.Val || cur.Val == head.Val {
			head.Val = cur.Val
			prev.Next = next
		} else {
			prev = cur
		}
		cur = next
		next = next.Next
	}
	if cur.Val == head.Val {
		prev.Next = next
	}
	return head.Next
}
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

# 官方思路

0A01E83A481A4919FAE203E7BB77FDD3

package main

import . "nc_tools"

/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * @param pHead ListNode类
 * @return ListNode类
 */
func deleteDuplication(pHead *ListNode) *ListNode {
	if pHead == nil {
		return nil
	}
	head := &ListNode{0, pHead}
	prev := head
	cur := prev.Next
	next := cur.Next
	for next != nil {
		if cur.Val == next.Val {
			next = next.Next
		} else if cur.Val == cur.Next.Val {
			cur = next
			next = next.Next
			prev.Next = cur
		} else {
			prev = cur
			cur = next
			next = next.Next
		}
	}
	if cur.Next != nil && cur.Val == cur.Next.Val {
		prev.Next = nil
	}
	return head.Next
}
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

# JZ18 删除链表的节点 (opens new window)

图片

package main

import . "nc_tools"
/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 
 * @param val int整型 
 * @return ListNode类
*/
func deleteNode(head *ListNode, val int) *ListNode {
	if head == nil {
		return nil
	}
	h := &ListNode{0, head}
	prev := h
	cur := h.Next
	for cur != nil {
		cur = cur.Next
		if prev.Next.Val == val {
			prev.Next = cur
		} else {
			prev = prev.Next
		}
	}
	return h.Next
}
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
上次更新: 2023/07/29, 17:09:37
day04
day06

← day04 day06→

最近更新
01
Go:GMP模型深入理解
01-10
02
rpc学习:进阶到gRPC
01-04
03
配置
12-12
更多文章>
Theme by Vdoing | Copyright © 2019-2024 xxcheng | 浙ICP备19024050号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式