Download Course 3:Linked List - 天府学院数据结构精品课程

Document related concepts
Transcript
Data Structures(数据结构)
Chapter3:Linked List
Vocabulary
Linear List
Linked List
Retrieval
Traversal
Node
Circularly Linked Lists
Doubly Linked Lists
Multilinked Lists
线性表
链表
检索
遍历
结点
循环链表
双向链表
多重链表
西南财经大学天府学院
2
3.1 Linear List
Definition: A linear list is a list in which each element
has a unique successor. Array is a typical linear list
structure.
Property: sequential
Element 1
Element 2
Element 3
Element 4
Figure 3.1 A Linear List
西南财经大学天府学院
3
3.1 Linear List


Linear List Can be Divided in two categories
General(Unordered, Ordered)
restricted(FIFO,LIFO)
Random List: No ordering of the data
Ordered List: the data are arranged according to a Key
Key: Use to identify the Data
(Simple array, array of records structure)
西南财经大学天府学院
4
3.1 Linear List
Four Operation often associate with Linear Lists
Insertion
Deletion
Retrieval(检索)
Traversal(遍历)
西南财经大学天府学院
5
3.1 Linear List
Insertion Location
Beginning of the list
In the middle of the list
At the end of the list
Figure 3.3 Ordered List Insertion
西南财经大学天府学院
6
3.1 Linear List
Deletion(General List)
Searching the location of the data to be deleted
Remove the data from the list
Figure 3.4 General List Deletion
西南财经大学天府学院
7
3.1 Linear List
Retrieval(General List)
Locate the Data in the list
No changing the contents of the lists
Figure 3.5 Linear List Retrieval
西南财经大学天府学院
8
3.1 Linear List
Traversal
A special case of retrieval
All elements need to be retrieved in sequence
Require loop algorithm
Other processes(Sorting, Calculate the total values)
西南财经大学天府学院
9
3.1 Linked list
Definition: A linked list is an ordered collection of data
in which each element contains the location of the next
element; that is , each element contains two parts: data
and link.
a singly linked list: a linked list contains only one link to
a single successor.
西南财经大学天府学院
10
3.1 Linked list
The major advantage of the linked list: the data of the
linked list can be easily inserted and deleted.
pHead
data
link
data
link
data
link
A linked list with a head pointer: pHead
pHead
An empty linked list
Nodes: The elements in a linked list are called nodes.
The node in a linked list are called self-referential
西南财经大学天府学院
11
Linked List Data Structure
Head Node Structure: It usually
contains two parts: a pointer and
metadata which are data about data
in the list.
Data Node Structure: The data type
for the list depends entirely on the
application. A typical data type is
metadata
like:
count
head
Head structure
data
link
List
count
<integer>
head
<pointer>
End List
dataType
key
<keyType>
field1 <…>
field2 <…>
…
fieldN <…>
End dataType
Node
data
<datatype>
link <pointer>
End Node
Data node structure
西南财经大学天府学院
12
3.2 Linked List Algorithms
Create List: it receives the head structure
and initializes the metadata for the list.
The pseudocode algorithms:
list
?
?
count
head
(a) before create
list.head = null
list.count = 0
Algorithm createList(ref list <metadata>)
Initializes metadata for a linked list.
Pre list is metadata structure passed
by reference
Post metadata initialized
1 list.head = null
2 list.count = 0
list
3 return
0
count
head
(b) after create
End createList
西南财经大学天府学院
13
Insert Node
1.Allocate memory for the new node and insert
data.
2.Point the new node to its successor.
3.Point the new node’s predecessor to the new
node.
We discuss four situation :
insert into empty list
insert at beginning
insert in middle
insert at end
西南财经大学天府学院
14
Insert into empty list:
0
count
75
head
(a) before add
pNew->link = list.head
List.head = pNew
pNew
Set link to null pointer
Point list to first node
75
1
count
head
pNew
(b) after add
西南财经大学天府学院
15
Insert at beginning
Logically,inserting into
an empty list is the
same as inserting
at the beginning of
Before add
75
1
count
a list.
head
pNew
39
pNew->link = list.head
List.head = pNew
After add
2
count
75
head
pNew
西南财经大学天府学院
39
16
Insert In Middle
Before add
39
2
count
75
head
pNew
52
pPre
pNew->link = pPre->link
pPre->link = pNew
After add
3
count
39
75
head
pPre
pNew
西南财经大学天府学院
52
17
Insert at end
Before add
3
count
39
52
75
head
pPre
134
pNew
pNew->link = pPre->link
pPre->link = pNew
After add
4
count
39
52
pPre
pNew
75
head
西南财经大学天府学院
134
18
Insert Node Algorithm
Algorithm insertNode (ref list
val pPre
val dataIn
1
allocate(pNew)
2
if (memory overflow)
< metadata >,
<node pointer>,
<dataType>)
end if
4
pNew->data=dataIn
5
if (pPre null)
Pre
List is metadata structure to
a valid list
1 return false
3
Insert data into a new node
in the linked list
pPre is pointer to data’s
logical predecessor
dataIn contains data to be
inserted
1 pNew->link =list.head
Post
2 list.head = pNew
6
1 pNew->link = pPre->link
data have been inserted in
sequence
2 pPre->link = pNew
Return
else
7
end if
8
list.count = list.count+1
9
Return ture
end insertNode
true if successful , false is
memory overflow
西南财经大学天府学院
19
Delete Node
this algorithm logically removes a node from the
linked list by:
1. changing various link pointers
2. physically deleting the node from dynamic
memory.
We discuss two situation :
delete first node (delete the only node in the list)
general delete case (delete the middle or last
node)
西南财经大学天府学院
20
Delete First Node
Before delete
3
count
39
75
134
75
134
head
pLoc
pPre
list.head = pLoc->link
recycle(pLoc)
After delete
(Recyled)
2
count
head
pLoc
pPre
西南财经大学天府学院
21
General Delete Case
Before delete
39
3
count
75
134
head
pPre
pLoc
pPre->link = pLoc->link
recycle(pLoc)
After delete
39
2
count
(Recycled)
134
head
pPre
西南财经大学天府学院
pLoc
22
Delete Node Algorithm
Algorithm DeleteNode (ref list
< metadata >,
val pPre
<node pointer>,
val pLoc
<node pointer>,
ref dataOut
1
Dataout = pLoc->data
2
if (pPre null)
and returns it to calling module.
<dataType>)
Pre
List is metadata structure to a
valid list
1 list.head = pLoc->link
3
Deletes data from a linked list
pPre is pointer to predecessor
node
else
1 pPre->link = pLoc->link
pLoc is a pointer to node to be
deleted
4
end if
5
list.count = list.count - 1
6
recycle(pLoc)
dataout is variable to received
deleted data
7
Return
Post
end deleteNode
data have been deleted and
returned to caller
23
西南财经大学天府学院
Search list
Search list: it is used by several algorithms to locate
data in a list. When we insert or delete or retrieve data
from a list, we need to search the list and find the data.
西南财经大学天府学院
24
Search list
Searches list and passes back address
of node containing target and its logical
predecessor.
Algorithm searchList (val list
<metadata> Pre
6
else
structure to a valid
ref pPre <node pointer> List is metadata
1 if (target equal pLoc->data.key)
list
ref pLoc <node pointer>
1 found = true
1
pPre = null
2
pLoc = list.head
3
4
5
pPre is pointer to predecessor node
ref target <key type>
pLoc is 2pointer
else variable for current
node
1 found = false
target is the being sought
3 end if
Post
Loop (pLoc not null AND target > pLoc->data.key)
endtoif first node with equal
pLoc7 point
1 pPre =pLoc
8 key
return found
/greater
-or- end
nullsearchList
if targer > key of last node
2 pLoc = pLoc->link
pPre points to largest node smaller
end loop
than key
If (pLoc null)
-or- null if targer < key of first node
1 found = false
Return
true if found , false if not found
25
西南财经大学天府学院
Unordered List Search:
The problem with unordered searches is that
multiple elements often satisfy the search criteria.
One simple solution is to return a list of all elements
that satisfy the criteria.
Retrieve Node:
1. Use search algorithm to locate the data in the list.
2. If the data are found, move the data to the output
area in the calling module and returns true.
3. If the data are not found, return false.
西南财经大学天府学院
26
algorithm retrieveNode (val list
val key
< metadata >,
<key type>,
ref dataOut <dataType>)
1
found = searchList(List, pPre, pLoc, key)
2
If (found)
1 dataOut = pLoc->data
3
End if
4
Return found
End retreiveNode
Algorithm emtpyList (val list <metadata>)
1 return (list.count equal to zero)
End emptyList
西南财经大学天府学院
27
Full List&ListCount
Algorithm fullList (val list <metatype>)
1
Allocate (pNew)
2
If (allocation successful)
1 recycle (pNew)
2 return false
3
End if
4
Return ture
End fullList
Algorithm listCount (val list <metatype>)
1
Return (list.count)
End listCount
西南财经大学天府学院
28
Traverse List
Algorithms of this kind start at the first node and examine
each node in succession until the last node has been
processed. Traverse list is used in changing a value in each
node, printing the list, summing a field in the list and so on.
step:
1. Set the walking pointer to the first node in the list.
2. Use a loop calling a process module and passes it the data
and then advances the walking pointer to the next node.
3. When the last node is processed, the walking pointer
becomes null and the loop terminates.
pWalker = list.head
Loop (pWalker not null)
process(pWalker ->data)
pWalker = pWalker ->link
End loop
西南财经大学天府学院
29
A approach in designing the traverse list
in this approach, the user controls the loop, calling
traverse to get next element in the list
Count
N
5
10
pos
•
15
head
20
…
95
100
moredata = getNext (list, 0, dataout)
Loop (moredata true)
process(dataout)
moredata = getNext (list, 1, dataout)
End loop
西南财经大学天府学院
30
Algorithm getNext ( ref list
<metatype>,
val fromWhere <Boolean>,
ref dataOut
1
<datatype> )
If (fromwhere is 0)
1 if (list.count is zero)
1 success = false
2 Else
1 list.pos = list.head
2 dataOut = list.pos->data
Traverses a linked list, each call return
the location of an element in the list
Pre
List is metadata structure to a valid
list
fromWhere is 0 start at the first
element
dataOut is variable to receive data
3 success = true
Post
dataOut contains data and true
returned
-or- if end of list returns false
3 end if
2
Else
1 if (list.pos->link null)
1 success = false
2 else
Return
1 list.pos = list.pos->link
2 dataOut = list.pos->data
3 success = true
true if next element located , false if
end of list
3 end if
3
End if
4
Return success
End getNext
西南财经大学天府学院
31
Destroy List
It deletes any nodes still in the list and recycles their
memory, then sets the metadata to a null list condition..
Algorithm destroyList (ref List <metadata>)
1
Loop (list.count not zero)
1 dltPtr = list.head
2 list.head = dltPtr->link
3 list.count = list.count – 1
4 recycle (dltPtr)
2
End loop
3
list.pos = null
4
Return
Delete all data in list
Pre
List is metadata structure to a valid list
Post
All data deleted
Return
End destroyList
西南财经大学天府学院
32
3.3 Processing A Linked list
LinkedList
createList
destroyList
(+)
getData
addNode
(+)
removeNode
printList
searchList
getNext
menu
searchList
insertNode
deleteNode
西南财经大学天府学院
33
Algorithm buildLinkedList
1
Print (welcome to exploring linked lists.)
2
CrateList (list)
3
Loop (option not to quit)
This program builds a linked list
that can be modified or printed by the
user.
1 option = menu ()
2 if (option add)
1 dataIn = getData()
2 addNode (list, dataIn)
3 elseif (option delete)
1 print (Enter key of data to be deleted.)
2 read (deleteKey)
3 removeNode (list, deleteKey)
4 elseif (option print)
1 printList (list)
5 endif
4
End loop
5
DestroyList (list)
6
Print (Exploration complete. Thank you.)
End buildLinkedList
西南财经大学天府学院
34
Algorithm menu
1
Print (……MENU……)
2
Print (A: Add new data.)
3
Print (D: Delete data.)
4
Print (P: Print list.)
5
Print (Q: Quit.)
6
Valid = false
7
Loop ( valid false)
Display a menu and read user option.
Pre
Nothing
Return
Valid choice
1 print ( Enter your choice:’’)
2 read (choice)
3 if (choice equal ‘A’ or ‘D’ or ‘P’ or ‘Q’)
1 valid = true
4 else
1 print ( Invalid choice. Choices are <A,D,P,Q> )
5 endif
8
End loop
9
Return choice
End menu
西南财经大学天府学院
35
Algorithm addNode ( ref list
<metadata>,
val dataIn <dataType>)
1
Found = searchList (list, pPre, pLoc, dataIn.key)
2
If (found)
1 print (Error: Data already in the list. NotAdd
added.)
data to a linked list
3
Else
Pre
1 success = insertNode (list, pPre, dataIn)List is metadata structure to a valid
list
2 if (success false)
dataIn are data to be inserted into list
1 print (Error: Out of memory. Program quitting.)
2 abort algorithm
3 end if
4
Post
Data have been inserted into list in key
sequence
Return
End addNode
西南财经大学天府学院
36
Algorithm removeNode (ref list
val key
<metadata>,
<keyType>)
1
Found = searchList (list, pPre, pLoc, key)
2
If (found)
1 deleteNode (list, pPre, pLoc, deleteData)
3
Else
1 print (Error: Key not in list.)
4
End if
5
Return
End removeNode
This algorithm deletes a node from the
linked list
Pre
List is metadata structure to a valid
list
key is the key to be located and
deleted
Post
the node has been deleted
-or- a warning message printed if not
found
西南财经大学天府学院
37
Algorithm printList ( val list
1
<metadata> )
If (emptyList (list))
1 print (No data in list.)
2
This algorithm traverses a linked list and
prints the key in each node.
Else
1 print (**** Begin Data Print ****)
2 count = 0
Pre
List is metadata structure to a valid list
3 moreData = getNext (list, 0, dataPtr)Post
All key have been printed
4 loop (moreData true)
1 count = count + 1
2 print (count, dataPtr->key)
3 moreData = getNext (list, 1, dataPtr)
5 end loop
3
End if
4
Return
End printlist
西南财经大学天府学院
38
3.4 List Applications
Append Lists:
list1
5
count pos head
5
10
15
20
25
7
12
17
22
27
list2
5
count pos head
Before Append
list1
5
count pos head
5
10
15
20
25
7
12
17
22
27
list2
5
count pos head
西南财经大学天府学院
After
Append
39
Algorithm appendTwolists
1
Pirint (This program creates two lists and then appends them)
2
Print (Enter first file name)
3
Read (fileName)
4
Open (fileName)
5
Build (list1, fileName)
6
printList (list1)
7
Print (Enter secondt file name)
8
Read (fileName)
9
Open (fileName)
10
Build (list2, fileName)
11
printList (list2)
12
Append (list1, list2)
13
printList (list1)
14
Return
End appendTwoLists
西南财经大学天府学院
40
Algorithm build ( ref list
val file
<metadata>,
<data file>)
1
CreateList (list)
2
Loop (not end of file)
1 read (file into dataIn)
2 searchList (list, pPre, pLoc, dataIn.key)
3 insertNode (list, pPre, dataIn)
3
End loop
4
Return
End build
西南财经大学天府学院
41
Algorithm append ( ref list1
<metadata>,
val list2
<metadata>)
1
If (list1.count zero)
1 list1.head = list2.head
2
Else
1 pLoc = list1.head
2 loop(pLoc->link not null)
1 pLoc = pLoc->link
3 end loop
4 pLoc->link = list2.head
3
End if
4
List1.count = list1.count + list2.count
5
Return
End append
西南财经大学天府学院
42
Array of lists
(count, pos,
and head)
西南财经大学天府学院
43
Algorithm arrayOf Lists
1
print (Begin array of linked lists)
2
Print (How many list do you want?)
3
Read (numLists)
4
buildArys (listArray, numLists)
5
printArys (listArray, numLists)
6
Print (End of arry of linked lists)
End arryOfLists
西南财经大学天府学院
44
Algorithm buildArrays (ref listArray
val numLists
1
row = 0
2
Loop (row < numLists)
<metadata>,
<integer>)
1 print (Enter file name)
2 read (fileName)
3 open (fileName)
4 build (listArray[row], fileName)
5 close (fileName)
6 row = row + 1
3
End loop
4
Return
End buildArrays
西南财经大学天府学院
45
Algorithm printArys (val listArray
<metadata>,
val numLists <integer> )
1
Row = 0
2
Loop (row < numLists)
1 printList (listArray[row])
2 row = row + 1
3
End loop
4
Return
End printAry
西南财经大学天府学院
46
3.5 Complex Linked List Structures
Circularly Linked Lists:In this structure, the last
node’s link points to the first node of the list.
N
count pos rear link
5
10
西南财经大学天府学院
95
47
The problem on searching Circularly Linked list:
What is the target does not exit?
The solution:
if we start at the fitst node, use the rear
pointer;
if we start at a middle node , we save the
starting node’s address, use the address
西南财经大学天府学院
48
Doubly Linked
In this structure, each node has a pointer to
both its successor and its predecessor.
List
count
B
head
rear
F
5
F
10
B: Backward
pointer
Doubly
B
B
95
F: Forward pointer
Linked List Insertion:
–Follow the basic patter.
–Need to connect both the forward and backward pointers.
西南财经大学天府学院
49
F
0
pNew
1
20
20
Before
After
Insert into null list or before first
node
3
2
pPre
40
20
pNew
20
30
Before
40
30
After
Insert between two nodes
西南财经大学天府学院
50
Algorithm insertDbl (ref list
<metadata>,
6 if (pPre->fore null)
val dataIn <dataType>)
1
1 list.rear = pNew
If (fulllist(list))
7 else
1 return 0
1 pSucc->back = pNew
2
End if
3
Found = searchList (list, pPre, pSucc,
dataIn.key)
11 list.count = list.count + 1
4
If (not found)
12 return (1)
8 end if
1 allocate (pNew)
5
End if
2 pNew->data = dataIn
6
Return (2)
3 if (pPre is null)
End insertDbl
1 pNew->back = null
2 pNew->fore = list.head
3 list.head = pNew
4 else
1 pNew->fore = pPre->fore
2 pNew->back = pPre
3 pPre->fore = pNew
5 end if
西南财经大学天府学院
51
Doubly Linked List Deletion
pPred pDlt
pSucc
3
25
75
50
Before delete
3
25
50
75
(Recycled)
After deleting 50
西南财经大学天府学院
52
Algorithm deleteDbl ( ref list
val pDlt
1
<metadata>,
<node pointer>)
If (pDlt null)
1 abort (Impossible condition in delete double)
2
End if
3
List.count = list.count - 1
4
If (pDlt->back not null)
1 pPred = pDlt->back
2 pPred->fore = pDlt->fore
5
Else
1 list.head = pDlt->fore
6
End if
7
If (pDlt->fore not null )
1 pSucc = pDlt->fore
2 pSucc->back = pDlt->back
8
Else
1 list.rear = pDlt->back
9
End if
10
Recycle (pDlt)
11
Return
End deleteDbl
西南财经大学天府学院
53
Multilinked Lists: It is a list with two or more logical
key sequences.
President
link
3
Pres
rear
Spouse
link
Sp
rear
Washington
1789
Cutis
Admas,J
1779
Smith
Jefferson
1801 Skelton
西南财经大学天府学院
54
Multilinked list
Build
Multilinked
insert
getData
Build
Node
Insert
Pres
Insert
Spouse
Search
Pres
Search
Spouse
55
西南财经大学天府学院
Multilinked List Delete:
The major variation for multilinked list delete:
need to reconnect the pointers for each logical
list.
One solution: use the spouse’s name from the
president search and then search the spouse list
to find the pointers that need to be updated, but
doing so can be very inefficient.
The standard solution: use a doubly linked list
for the spouse links.
西南财经大学天府学院
56
3.6 Summary
A linear list is a list in which each element has a unique
successor.
Linear list can be divided into tow categories: general
and restricted.
In a general list, data can be inserted and deleted anywhere
and there are no restrictions on the operations that can be used
to process the list.
General lists can be further divided into random lists and
ordered list.
In a random list, there is no ordering of the data.
西南财经大学天府学院
57
In an ordered list, the data dare arranged according to a
key,which is one or more fields used to identify the data
or control their use.
In a restricted list, data ,can be added or deleted at the
end of the structure and processing is restricted to the
operations on the data at the ends of the list.
Two common restricted list structures are stacks, (last infist out [LIFO] lists) and queues (fist in-first out [FIFO]
lists).
Four common operations are associated with linear
lists: insertion, deletion, retrieval, and traversal.
A linked list is an ordered collection of data in
which each element contains the location (address)
of the next element; that is, each element contains
two parts: data and link.
西南财经大学天府学院
58
A head node is a data structure that contains
metadata about the list, such as a count, a head
pointer to the first node, and a rear pointer to the
last node. It may contain any other general list data
required by the use of the structure.
The node in s singly linked list contains only one
link to a single successor unless it is the last, in
which case it is not linked to any other node.
When we want to insert into a linked list, we must
consider four cases: adding to the empty list,
adding at the beginning, adding to the middle, and
adding at the end.
西南财经大学天府学院
59
When we want to delete a node from a list, we must
consider two case: delete the first node or delete
any other node.
To search a linked list for an item, we use the
ordered list search.
Traversing a linked list means going through the
list, node by node, and processing each node.
Three examples of list traversals are counting the
number of the nodes, printing the contents of
nodes, and summing the values of one or more
fields.
西南财经大学天府学院
60
• A header node contains the same metadata found
in the head structure and shares the pointer
structure with the data node. It is physically
positioned so that it is always the first node in the
linked list.
• A circularly linked list is a list in which the last
node’s link points to the first node of the list.
• A doubly linked list is a linked list in which each
node has pointer to both its successor and its
predecessor.
• A multilinked list is a linked list with two or more
logical list.
西南财经大学天府学院
61
Exercises
西南财经大学天府学院
62
Exercises
西南财经大学天府学院
63
Exercises
西南财经大学天府学院
64
Exercises
西南财经大学天府学院
65