-
Notifications
You must be signed in to change notification settings - Fork 306
/
Copy pathll.py
107 lines (90 loc) · 2.23 KB
/
ll.py
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
#!/usr/bin/python
#coding:utf-8
#=======================================================================
# Author: Yu Zhou
# Singly Linked List
#=======================================================================
from random import randint
class Node(object):
#Constructor
def __init__(self, val, next = None):
self.val = val
self.next = next
class LinkedList(object):
#Constructor
def __init__(self, head = None, size = None):
self.head = head
self.size = size
#Display
def __str__(self):
res = []
cur = self.head
while cur:
res.append(str(cur.val))
cur = cur.next
return ' -> '.join(res)
#在头Insert
def insert_head(self, val):
if self.head == None:
self.head = Node(val)
else:
temp = Node(val) #创建Temp Node
temp.next = self.head #指向Head
self.head = temp #把head的reference改到这个Temp Node
#在末尾Insert
def insert_tail(self, val):
if self.head == None:
self.head = Node(val)
else:
cur = self.head
temp = Node(val)
while cur.next: #位移
cur = cur.next
cur.next = temp
#Generate Insert 10位数
def generate(self):
for _ in xrange(10):
self.insert_tail(randint(0,9))
#Insert自定义多位数
def insert_multiple(self, val):
for v in val:
self.insert_tail(v)
#Search
def search(self, val):
if self.head == None:
raise ValueError("List is empty")
cur = self.head
while cur:
if cur.val == val:
return True
else:
cur = cur.next
return False
#Delete V1 using Prev
def delete_1(self, val):
if self.head == None:
return self.head
cur = self.head
prev = None
while cur:
if cur.val == val:
if prev:
prev.next = cur.next
else:
self.head = cur.next
prev = cur
cur = cur.next
#Delete V2 not using Prev
def delete_2(self, val):
if self.head == None:
return self.head
cur = self.head
#Edge case
if cur.val == val:
self.head = cur.next
#The rest
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next