来源:自学PHP网 时间:2020-09-27 14:45 作者:小飞侠 阅读:次
[导读] python/golang 删除链表中的元素...
|
今天带来python/golang 删除链表中的元素教程详解
先用使用常规方法,两个指针: golang实现:
type Node struct {
value int
next *Node
}
type Link struct {
head *Node
tail *Node
lenth int
}
// 向链表中添加元素
func (link *Link) add(v int) {
if link.lenth == 0 { // 当前链表是空链表
link.head = &Node{v, nil}
link.tail = link.head
link.lenth = 1
} else {
newNond := &Node{v, nil}
link.tail.next = newNond
link.tail = newNond
link.lenth += 1
}
}
// 删除链表中的元素(双指针)
func (link *Link) remove(v int) {
if link.lenth == 0 {
fmt.Println("空链表,不支持该操作")
return
}
var previous *Node = nil
for current := link.head; current != nil; current = current.next {
if current.value == v {
if current == link.head { // 要删除的是头节点
link.head = current.next
} else if current == link.tail { // 要删除的是尾节点
previous.next = nil
link.tail = previous
} else { // 要删除的是中间的节点
previous.next = current.next
}
link.lenth -= 1
break
}
previous = current
}
}
// 打印链表
func (link *Link) printList() {
if link.lenth == 0 {
fmt.Println("空链表")
return
}
for cur := link.head; cur != nil; cur = cur.next {
fmt.Printf("%d ", cur.value)
}
fmt.Println()
}
python实现:
class Node:
def __init__(self, value, next):
self.value = value
self.next = next
def __str__(self):
return str(self.value)
class Link:
def __init__(self):
self.head = None
self.tail = None
self.lenth = 0
# 向链表中添加元素
def add(self, v):
if self.lenth == 0: # 当前链表是空链表
self.head = Node(v, None)
self.tail = self.head
self.lenth = 1
else:
new_node = Node(v, None)
self.tail.next = new_node
self.tail = new_node
self.lenth += 1
# 打印链表
def print(self):
if self.lenth == 0:
print('空链表')
return
cur = self.head
while True:
if cur == None:
print()
break
print(cur, end=' ')
cur = cur.next
# 删除链表中的元素
def remove(self, v):
if self.lenth == 0:
return
cur = self.head
pre = None
while True:
if cur.value == v:
if cur == self.head: # 要删除的是头节点
self.head = cur.next
elif cur == self.tail: # 要删除的是尾节点
pre.next = None
self.tail = pre
else: # 要删除的是中间的节点
pre.next = cur.next
self.lenth -= 1
break
pre = cur
cur = cur.next
if cur == None:
print("未找到", v)
break
只使用使用一个指针实现链表的删除:
|
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com