Use Python to Implement a Linked List with Sorting and Searching
We will use Python to implement a simple linked list and add sorting and searching functionality to it. A linked list is a common data structure consisting of a series of nodes, each containing data and a pointer to the next node.
Example
class
Node:
def
init
(
self
,
data
)
:
self
.
data
=
data
self
.
next
=
None
class
LinkedList:
def
init
(
self
)
:
self
.
head
=
None
def
append
(
self
,
data
)
:
new_node
=
Node
(
data
)
if
not
self
.
head
:
self
.
head
=
new_node
return
last_node
=
self
.
head
while
last_node.
next
:
last_node
=
last_node.
next
last_node.
next
=
new_node
def
display
(
self
)
:
current
=
self
.
head
while
current:
(
current.
data
,
end
=
" -> "
)
current
=
current.
next
(
"None"
)
def
sort
(
self
)
:
if
not
self
.
head
:
return
sorted_list
=
[
]
current
=
self
.
head
while
current:
sorted_list.
append
(
current.
data
)
current
=
current.
next
sorted_list.
sort
(
)
self
.
head
=
None
for
item
in
sorted_list:
self
.
append
(
item
)
def
search
(
self
,
key
)
:
current
=
self
.
head
while
current:
if
current.
data
==
key:
return
True
current
=
current.
next
return
False
Example usage
ll
=
LinkedList
(
)
ll.
append
(
3
)
ll.
append
(
1
)
ll.
append
(
4
)
ll.
append
(
2
)
(
"Original linked list:"
)
ll.
display
(
)
ll.
sort
(
)
(
"Sorted linked list:"
)
ll.
display
(
)
(
"Search for element 4:"
,
ll.
search
(
4
)
)
(
"Search for element 5:"
,
ll.
search
(
5
)
)
Code analysis:
Nodeclass: represents a node in the linked list, containing datadataand a pointer to the next nodenext。LinkedListclass: represents the linked list, containing a pointer to the headhead。appendmethod: add a new node at the end of the linked list.displaymethod: print all elements in the linked list.sortmethod: sort the elements in the linked list. First extract the data in the linked list into a list, then sort the list, and finally reinsert the sorted data back into the linked list.searchmethod: search for a specified element in the linked list; if found, returnTrue; otherwise, returnsFalse。
Output result:
原始链表:
3 -> 1 -> 4 -> 2 -> None
Sorted linked list:
1 -> 2 -> 3 -> 4 -> None
查找元素 4: True
查找元素 5: False
Python3 Examples