Anda di halaman 1dari 8

Examples and Exercises on Linked Lists:

1. BuildOneTwoThree() Function
Here is simple function which uses pointer operations to build the list {1, 2, 3}. This
function demonstrates how calls to malloc() and pointer assignments () wor! to build a
pointer structure in the heap.
"#
$uild the list {1, 2, 3} in the heap and store its head pointer in a local stac! %ariable.
returns the head pointer to the caller.
#"
struct node# $uild&neTwoThree() {
struct node# head '())*
struct node# second '())*
struct node# third '())*
head malloc(si+eof(struct node))* "" allocate 3 nodes in the heap
second malloc(si+eof(struct node))*
third malloc(si+eof(struct node))*
head,-data 1* "" setup first node
head,-ne.t second* "" note/ pointer assignment rule
second,-data 2* "" setup second node
second,-ne.t third*
third,-data 3* "" setup third lin!
third,-ne.t '())*
"" 0t this point, the lin!ed list referenced b1 2head2
"" matches the list in the drawing.
return head*
}
3.ercise
4/ 5rite the code with the smallest number of assignments () which will build the
abo%e memor1 structure.
6t re7uires 3 calls to malloc().
3 int assignments () to setup the ints.
8 pointer assignments to setup head and the 3 ne.t fields.
5ith a little cle%erness and !nowledge of the 9 language, this can all be done with :
assignment operations ().
2. )ength() ;unction
The )ength() function ta!es a lin!ed list and computes the number of elements in the list.
)ength() is a simple list function.
"# <i%en a lin!ed list head pointer, compute and return the number of nodes in the list. #"
int )ength(struct node# head) {
struct node# current head*
int count =*
while (current > '())) {
count??*
current current,-ne.t*
}
return count*
}
3.ercise
%oid )engthTest() {
struct node# m1)ist $uild&neTwoThree()*
int len )ength(m1)ist)* "" results in len 3
}

5hat if we said head '())* at the end of )ength() @ would that mess up the m1)ist
%ariable in the callerA
0ns/ 'o. head is a local which was initiali+ed with a cop1 of the actual parameter, but
changes do not automaticall1 trace bac! to the actual parameter. 9hanges to the local
%ariables in one function do not affect the locals of another function.
3.ercise
4/ 5hat if the passed in list contains no elements, does )ength() handle that case
properl1A
0ns/ Bes. The representation of the empt1 list is a '()) head pointer. Trace
)ength() on that case to see how it handles it.
3. 9orrect Cush() 9ode
The list is passed %ia a pointer to the head pointer. 6n the code, this amounts to use of DED
on the parameter in the caller and use of D#D on the parameter in the callee. 6nside Cush(),
the pointer to the head pointer is named 2headFef2 instead of Gust 2head2 as a reminder
that it is not Gust a simple head pointer.
"# Ta!es a list and a data %alue. 9reates a new lin! with the gi%en data and pushes it onto
the front of the list. The list is not passed in b1 its head pointer. 6nstead the list is passed
in as a 2reference2 pointer to the head pointer ,, this allows us to modif1 the callerDs
memor1. #"
%oid Cush(struct node## headFef, int data) {
struct node# new'ode malloc(si+eof(struct node))*
new'ode,-data data*
new'ode,-ne.t #headFef* "" The D#D to dereferences bac! to the real head
#headFef new'ode* "" ditto
}
%oid CushTest() {
struct node# head $uildTwoThree()*"" suppose this returns the list {2, 3}
Cush(Ehead, 1)* "" note the E
Cush(Ehead, 13)*
"# head is now the list {13, 1, 2, 3} #"
}
8. 9op1)ist()
9onsider a 9op1)ist() function that ta!es a list and returns a complete cop1 of that list.
&ne pointer can iterate o%er the original list in the usual wa1. Two other pointers can
!eep trac! of the new list/ one head pointer, and one tail pointer which alwa1s points to
the last node in the new list. The first node is done as a special case, and then the tail
pointer is used in the standard wa1 for the others...
struct node# 9op1)ist(struct node# head) {
struct node# current head* "" used to iterate o%er the original list
struct node# new)ist '())* "" head of the new list
struct node# tail '())* "" !ept pointing to the last node in the new list
while (current > '())) {
if (new)ist '())) { "" special case for the first new node
new)ist malloc(si+eof(struct node))*
new)ist,-data current,-data*
new)ist,-ne.t '())*
tail new)ist*
}
else {
tail,-ne.t malloc(si+eof(struct node))*
tail tail,-ne.t*
tail,-data current,-data*
tail,-ne.t '())*
}
current current,-ne.t*
}
return(new)ist)*
}
Croblems/
1. <i%en a list and an inde., return the data in the nth node of the list. The nodes are
numbered from =. 0ssert fails if the inde. is in%alid (outside =..lengh,1).
int <et'th(struct node# head, int inde.) {
"" Bour code
}
2. 5rite a function Helete)ist() that ta!es a list, deallocates all of its memor1 and sets its
head pointer to '()) (the empt1 list).
Hint/ (se pointer to the head pointer
3. 0 more general %ersion of Cush(). <i%en a list, an inde. DnD in the range =..length, and a
data element, add a new node to the list so that it has the gi%en inde..
%oid 6nsert'th(struct node## headFef, int inde., int data) {
"" 1our code...
}
8. 5rite a Iorted6nsert() function which gi%en a list that is sorted in increasing order, and
a single node, inserts the node into the correct sorted position in the list. 5hile Cush()
allocates a new node to add to the list, Iorted6nsert() ta!es an e.isting node, and Gust
rearranges pointers to insert it into the list.
%oid Iorted6nsert(struct node## headFef, struct node# new'ode) {
"" Bour code...
}
J. 5rite an 0ppend() function that ta!es two lists, DaD and DbD, appends DbD onto the end of
DaD, and then sets DbD to '()) (since it is now trailing off the end of DaD).
%oid 0ppend(struct node## aFef, struct node## bFef) {
"# Bour code...#"
}
K. <i%en a list, split it into two sublists @ one for the front half, and one for the bac! half.
6f the number of elements is odd, the e.tra element should go in the front list. Io
;ront$ac!Iplit() on the list {2, 3, J, :, 11} should 1ield the two lists {2, 3, J} and {:,
11}. <etting this right for all the cases is harder than it loo!s. Bou should chec! 1our
solution against a few cases (length 2, length 3, length8) to ma!e sure that the list
gets split correctl1 near the short,list boundar1 conditions. 6f it wor!s right for length8,
it probabl1 wor!s right for length1===. Bou will probabl1 need special case code to deal
with the (length L2) cases.
"# Iplit the nodes of the gi%en list into front and bac! hal%es, and return the two lists
using the reference parameters. 6f the length is odd, the e.tra node should go in the front
list. #"
%oid ;ront$ac!Iplit(struct node# source, struct node## frontFef, struct node## bac!Fef)
{
"# Bour code...#"
}
:. 5rite a Femo%eHuplicates() function which ta!es a list sorted in increasing order and
deletes an1 duplicate nodes from the list. 6deall1, the list should onl1 be tra%ersed once.
"# Femo%e duplicates from a sorted list. #"
%oid Femo%eHuplicates(struct node# head) {
"# Bour code...#"
}
M. This is a %ariant on Cush(). 6nstead of creating a new node and pushing it onto the
gi%en list, No%e'ode() ta!es two lists, remo%es the front node from the second list and
pushes it onto the front of the first.
"# Ta!e the node from the front of the source, and mo%e it to the front of the dest.6t is an
error to call this with the source list empt1. #"
%oid No%e'ode(struct node## destFef, struct node## sourceFef) {
"# Bour code #"
}
O. 5rite an iterati%e Fe%erse() function that re%erses a list b1 rearranging all the .ne.t
pointers and the head pointer. 6deall1, Fe%erse() should onl1 need to ma!e one pass of
the list. The iterati%e solution is moderatel1 comple..
Hints:
2Cush2 Fe%erse Hint
6terate through the main list. No%e each node to the front of the result list as 1ou go. 6tDs
li!e doing a Cush() operation with each node, e.cept 1ou use pointer re,arrangement on
the e.isting node instead of allocating a new node. Bou can use No%e'ode() to do most
of the wor!, or hand code the pointer re,arrangement.
23 Cointers2 Hint
This strateg1 is not as good as the 2Cush2 strateg1. 6nstead of running a single 2current2
pointer down the list, run three pointers (front, middle, bac!) down the list in order/ front
is on one node, middle is Gust behind it, and bac! in turn is one behind middle. &nce the
code to run the three pointers down the list is clear and tested in a drawing, add code to
re%erse the .ne.t pointer of the middle node during the iteration. 0dd code to ta!e care of
the empt1 list and to adGust the head pointer itself.
"# Fe%erse the gi%en lin!ed list b1 changing its .ne.t pointers and its head pointer. Ta!es
a pointer (reference) to the head pointer. #"
%oid Fe%erse(struct node## headFef) {
"# 1our code... #"
}
Feferences/
1. $asic and a detailed e.planation about lin!ed lists
http://cslibrary.stanford.edu/103/LinkedListBasics.pdf
2. )in!ed )ist Croblems
http://cslibrary.stanford.edu/105/LinkedListProblems.pdf
Clease go through the abo%e two lin!s for more info.

Anda mungkin juga menyukai