题目描述
Technical reflection, little happiness.
判断是否存在环:
(fast != None) && (fast.next != None)寻找环入口:
使用start,end两个指针记录下标
两个指针由两端向中间移动。
- IndentationError: unindent does not match any outer indentation level
- TabError: inconsistent use of tabs and spaces in indentation
这个错误就像全角半角符号一样让人抓狂,要是想整死一个程序员,就悄悄把他代码里的半角字符换成全角的,他就会开始漫长又愉快的debug~
你永远不知道自己什么时候会出现缩进错误,即使你认为所有地方都使用了tab键ヽ(`Д´)ノ︵ ┻━┻ ┻━┻
解决办法
点击这里,变成tab,文档里的空格就自动变成tab了,你会看到有些小地方闪了一下,就是那些地方的空格让你出错/微笑。
1 | class ListNode: |
实现基本操作:

使用表头结点:
表头结点是链表的第一个结点,除了值被忽略以外和其它结点一致,但它不被当做链表中的实际元素。
头结点的存在使得空链表与非空链表处理一致,也方便对链表的开始结点的插入或删除操作。
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108class SinLinkedList:
def __init__(self):
self.head = ListNode(None)
# 是否为空
def isEmpty(self):
return self.length() == 0
# 清空
def clear(self):
self.head = ListNode(None)
# 链表长度
def length(self):
cnt = 0
curr = self.head
while curr.next is not None:
cnt += 1
curr = curr.next
return cnt
# 在链表末尾添加结点
def append(self, val):
node = ListNode(val)
if self.head is None:
self.head = node
else:
p = self.head
while p.next:
p = p.next
p.next = node
# 在指定位置添加结点
def insert(self, idx, value):
if self.isEmpty():
print('链表为空')
p = self.head
new = ListNode(value)
while p and idx > 0:
p = p.next
idx -= 1
# 说明没有那么多结点
if idx > 0:
print('超出链表长度')
else:
q = p.next
p.next = new
new.next = q
# 删除指定位置的结点
def delete(self, idx):
if self.isEmpty():
print('链表为空')
p = self.head
while p and idx > 0:
p = p.next
idx -= 1
# 说明没有那么多结点
if idx > 0:
print('超出链表长度')
else:
p.next = p.next.next
# 替换指定位置结点值
def replace(self, idx, newValue):
if self.isEmpty():
print('链表为空')
p = self.head
new = ListNode(newValue)
while p and idx > 0:
p = p.next
idx -= 1
# 说明没有那么多结点
if idx > 0:
print('超出链表长度')
else:
q = p.next.next
p.next = new
new.next = q
# 查找第idx个结点值
def search(self, idx):
if self.isEmpty():
print('链表为空')
return
p = self.head
while p.next and idx > 0:
p = p.next
idx -= 1
if idx > 0:
print('超出链表长度')
else:
return p.val
# 查找指定值所在结点位置
def index(self, value):
if self.isEmpty():
print('链表为空')
return
p = self.head
idx = 0
while p.next and not p.val == value:
p = p.next
idx += 1
return idx - 1
1 | l = SinLinkedList() |
特点:从表中任意结点出发均可找到链表中其它结点,查找效率高。
1 | class ListNode: |
实现基本操作:
1 | class SinCycLinkedList: |
1 | l = SinCycLinkedList() |
判断是否存在环:
(fast != None) && (fast.next != None)寻找环入口: