Linked List in Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

CSC248

Jun-Oct 2013

CSC 248
Linked Lists

Linked Lists
What is a linked lists?

Definition: a list of items, called nodes, in which the order of


the nodes is determined by the address,
address called the link
link,
stored in each node
Every node in a linked list has two components:

one to store relevant information


one to store address (the link) of next node in list

Address of first node in list stored in separate location,


called the head or first
D type off eachh node
Data
d depends
d
d on the
h specific
ifi
application kind of data being processed
link component of each node is a reference variable

Prepared by: Pn Yusnita Sokman

CSC248
Jun-Oct 2013

Cont

Structure of a node

Structure of a linked list

Linked Lists: Some Properties


The address of the first node in a linked list is stored in
the reference variable head
E h node
Each
d has
h two
t
components:
t

data: contains the necessary information about the items of the


list
link: contains the address of the next node

head should always point to the first node

Prepared by: Pn Yusnita Sokman

CSC248
Jun-Oct 2013

Linked Lists: Some Properties


Linked list basic operations:

Search the list to determine whether a particular item is in the


list
Insert an item in the list
Delete an item from the list

Operations require traversal of the list


Given a reference variable to the first node of the list,
g each of the nodes of the list
stepp through
Traverse a list using a reference variable of the same type
as head

Linked Lists: Some Properties

Prepared by: Pn Yusnita Sokman

CSC248
Jun-Oct 2013

Linked Lists: Some Properties

Insertion
p = head.link;//p points to the node with info 65
newNode = new LinkedListNode();//create the object newNode
newNode.info = 50;//store 50 in the object newNode

Prepared by: Pn Yusnita Sokman

CSC248
Jun-Oct 2013

Insertion
//insert newNode after p
newNode.link = p.link;
p.link = newNode;

Insertion
//insert newNode after p
newNode.link = p.link;
p.link = newNode;

head

45

65

34

76

newNode

50

Figure 4-10 list after the statement p.link = newNode; executes

10

Prepared by: Pn Yusnita Sokman

CSC248
Jun-Oct 2013

Deletion
p = head.link;
p.link = p.link.link;

Node to be deleted is 34

11

Deletion
p = head.link;
head

q = p.link;

45

65
p

34

76

p.link = q.link;
q = null;
head

45

65

34

76

a) List after the statement p.link = q.link; execute


head

45

65

76
34

p
q

b) List after the statement q = null;executes


12

Prepared by: Pn Yusnita Sokman

CSC248
Jun-Oct 2013

Building a Linked List

Two ways to build a linked list:

fforward
d a new node
d is always
l
inserted
d at the
h end
d off the
h
linked list
backward a new node is always inserted at the beginning of
the linked list

13

Data Structures Using Java

Building a Linked List Forward

Assume that we process the following data:


2 15 8 24 34

What is needed to build a linked list forward:

Need three reference variables:

a reference variable for the first node


a reference variable for the last node
a reference variable for the new node being added

14

Prepared by: Pn Yusnita Sokman

CSC248
Jun-Oct 2013

Building a Linked List

Here are the steps to adding a new node to the end


of a linked list:

Read
R
d and
d store a number
b in
i num
Create the object newNode
Copy the value of num into the info field of newNode
Initialize the link field of newNode to null
If first is null, the list is empty; make first and last point to
newNode
else the list is not empty

insert newNode at the end of the list

set last so that it points to the actual last node in the list

(Refer page 234 238)

15

Building a Linked List Forward

16

Prepared by: Pn Yusnita Sokman

CSC248
Jun-Oct 2013

Building a Linked List Forward

17

Building a Linked List Forward

18

Prepared by: Pn Yusnita Sokman

CSC248
Jun-Oct 2013

Building a Linked List Backward

Assume that we process the following data:


2 15 8 24 34

What is needed to build a linked list backward:

Need two reference variables:

a reference variable for the first node


a reference variable for the new node being added

Because of the new node is always inserted at the beginning of


the list, we do not need to know the end of the list, so the
reference variable last is not needed.

19

Building a Linked List Backward

In pseudocode, the algorithm is


1. Initialize first to NULL.
2. For each item in the list:
a. Create the object, newNode.
b. Store the item in newNode.
c. Insert newNode before first.
d. Update the value of the reference variable first.

(Refer page 239 )

20

Prepared by: Pn Yusnita Sokman

10

CSC248
Jun-Oct 2013

Building a Linked List Backward


Empty list

first

newNode with info 2

2
newNode

first

Insert newNode before first

2
newNode

first

List and newNode with info 15

15
newNode

21

Building a Linked List Backward


first

15
newNode

head

34

24

15

newNode

List after building it backward

22

Prepared by: Pn Yusnita Sokman

11

CSC248
Jun-Oct 2013

Advantages of Linked Lists

Linked lists are dynamic

Linked lists can be maintained in sorted order simply


by inserting each new element at the proper point in
the list

The list can grow or shrink as necessary

Existing list elements do not need to be moved

Linked lists are non-contiguous

The logical
Th
l i l sequence off the
h iitems iin the
h structure is
i
decoupled from any physical ordering in memory

23

Types of Linked Lists

Singly Linked Lists


Doubly Linked Lists
Circular Linked Lists

24

Prepared by: Pn Yusnita Sokman

12

CSC248
Jun-Oct 2013

Types of Linked List

Singly linked list


head

represents
null
a1

a2

a3

a4

Each element is contained in an object, called an Entry object,


that also includes a reference, called a link, to the Entry object
that holds the next element
in the list.

25

Types of Linked List

Doubly linked list


forward traversal
Doubly Linked List.
head

next

x1

x2

x3

x4

prev
backward traversal

If each Entry object also includes a link to the Entry


object that holds the previous element in the list, we
have a doubly linked list.
26

Prepared by: Pn Yusnita Sokman

13

CSC248
Jun-Oct 2013

Doubly Linked List

Every node:

has a next reference variable and a back reference variable


(
(except
t th
the llastt node)
d ) contains
t i th
the address
dd
off the
th nextt node
d
(except the first node) contains the address of the previous
node

Can be traversed in either direction

27

Circular Linked Lists

A linked list in which the last node points to the first


node is called a circular linked list

Circular Linked List.


head

x1

x2

...

xn

28

Prepared by: Pn Yusnita Sokman

14

CSC248
Jun-Oct 2013

Cont

Advantage: can traverse in forward or reverse direction


even after you have passed the last or first node

Can visit all the list elements from any starting point

Can never fall off the end of a list


Disadvantage: infinite loop!

29

Linked List As An ADT

Prepared by: Pn Yusnita Sokman

15

CSC248
Jun-Oct 2013

Basic Operations

Basic operations on a linked list are:

Initialize the list


Ch k whether
Check
h th th
the lilistt iis empty
m t
Output the list
Find length of list
Get info from last node
Search for a given item
Insert an item
Delete an item
Replaces the element at a specified index with a specified
element

31

Linked List vs. Array List

Insertions and removals can be made without moving


any elements; only the links are altered.
There are 6 methods which are not available in the
arraylist class:

public boolean addFirst( Object element)


public boolean addLast(Object element)
public Object getFirst()
public Object getLast()
public Object removeFirst()
public Object removeLast()

32

Prepared by: Pn Yusnita Sokman

16

CSC248
Jun-Oct 2013

Cont

Initialize linked list

The following creates an empty Linked List object called


numList

LinkedList numList = new LinkedList();

numList

head

33

Cont

Insert a new item to the end of list object


LinkedList numList =
numList add("1");
numList.add(
1 ); or
numList.add("2"); or
numList.add("3"); or
numList.add("4"); or

new LinkedList();
numList addLast("1");
numList.addLast(
1 );
numList.addLast(2");
numList.addLast(3");
numList.addLast(4");

head

represents
null
1

34

Prepared by: Pn Yusnita Sokman

17

CSC248
Jun-Oct 2013

Cont

Insert a new item to the beginning of list object


LinkedList numList = new LinkedList();
numList addFirst("1");
numList.addFirst(
1 );
numList.addFirst("2");
numList.addFirst("3");
numList.addFirst("4");

head

represents
null
4

35

Cont

Insert a new item between two nodes


LinkedList numList = new LinkedList();
numList add("1");
numList.add(
1 );
numList.add("2");
numList.add("3");
numList.add("4");
numList.add(3,"5");
head

36

Prepared by: Pn Yusnita Sokman

18

CSC248
Jun-Oct 2013

Cont

Delete a node
numList.remove(2); // from the nth node

head

37

Cont

Delete a node
numList.removeFirst();//from the beginning

head

38

Prepared by: Pn Yusnita Sokman

19

CSC248
Jun-Oct 2013

Cont

Delete a node
numList.removeLast(); // from the end

head

39

Cont

Check whether the list is empty and find length of list


LinkedList numList = new LinkedList();
numList.add("1");
numList.add("2");
numList.add("3");
numList.add("4");
if(numList.isEmpty())
System.out.println("Empty List");
else
{
S t
System.out.println("Size:
t
i tl ("Si
"+ numList.size());
Li t i ())
System.out.println(numList);
}

40

Prepared by: Pn Yusnita Sokman

20

CSC248
Jun-Oct 2013

Cont

Get info from last node

System.out.println(
System
out println(Get
Get info from last node: "
+ (numList.size() - 1));
System.out.println(Get info from last node: "
+numList.getLast());

41

Cont

Search for a given item

Search the element at a specified position

Search the first element in the list

System out println(numList get(1));


System.out.println(numList.get(1));
System.out.println(numList.getFirst());

Search the last element in the list

System.out.println(numList.getLast());

42

Prepared by: Pn Yusnita Sokman

21

CSC248
Jun-Oct 2013

Cont

Replaces the element at a specified index with a specified


element

Return the previous occupant(the element replaced) at


position index

System.out.println(numList.set(2,"5"));

43

Exercise 1

Assume that you are given TWO nodes. Node 1 contains


the integer value of 1 and node 2 contains the integer
value 2.
2 If you are going to create a linked list of these
two nodes in order, draw the diagram to show the
structure of the linked list with head and tail
head

tail

44

Prepared by: Pn Yusnita Sokman

22

CSC248
Jun-Oct 2013

Exercise 2

Based on Exercise 1, where we have two nodes already in


the linked list, draw a complete diagram to show the
contents of the linked list after each of the following
operations:

Insert three(3) integers at the front, which are 8, 10 and 66.


Insert another three (3) integers at the back, which are 68, 3
and 1.
Remove one(1) element from the front.
Remove two(2) elements from the back.
Remove all even integers.

45

Answer
head

tail

head

66

10

tail

head

66

10

68

tail

46

Prepared by: Pn Yusnita Sokman

23

CSC248
Jun-Oct 2013

Answer
head

10

10

68

tail

head

68

tail

head

tail

47

Exercise 3
public class Number
{
pri ate int n
private
n;
public Number(){ n=0; }
public Number(int n) { this.n=n; }
public int getN() { return n; }
}

Based on the class Number above


above, write a program for
the following processes:

Prompts user to enter twenty (20) integer numbers and store


them into an LinkedList object named as numLinkList.

48

Prepared by: Pn Yusnita Sokman

24

CSC248
Jun-Oct 2013

Exercise 3(cont)

Remove all numbers that can be divided by 5 from the


numLinkList and store them into a LinkedList object
named as num5LinkList.
Display the content of the numLinkList and
num5LinkList.
Read and verify the numbers in num5LinkList, where if the
number is even number, store it on a list named as evenList
otherwise store it on list named oddList.
Display
p y the content of the evenList and oddList.
Find and display the largest and smallest number in the
evenList.
Calculate and display the sum of all numbers in the oddList.

49

Exercise 4

50

Prepared by: Pn Yusnita Sokman

25

CSC248
Jun-Oct 2013

End of Chapter
Puan Yusnita Sokman

51

Prepared by: Pn Yusnita Sokman

26

You might also like