You are on page 1of 118

Translated from Turkish to English - www.onlinedoctranslator.

com

lists
Assist. Assoc. Dr. Aybars UĞUR,
Assist.Prof.Dr. Prepared from M. Ali
Akcayol lecture notes and foreign
resource compilations.

one
2nd

LISTS
- Lists
in daily life; shopping lists, invitations,
phone lists etc. used.

- Programming in terms of list; between them


can be viewed as a collection of data with a linear
relationship.

- Different
forms of lists are used in data
structures and different operations are
performed on them.
3

Linear Lists (Arrays)


- Arrays are structures that make up linear lists. The features of these
structures can be listed as follows:

- Linearlists have continuity. If we consider the array data structure, the


elements in this data structure are of the same type and are stored
sequentially in memory.

- Array elements cannot contain other elements. When adding


elements to the array (except at the end of the array), the
array elements must be swapped.

- The array is defined at the beginning of the program and the memory space to be allocated is
specified. The number of elements cannot be increased or decreased while the program is
running.
4

Linear Lists (Arrays)


- Unused fields may occur when the size of the array is
defined too large from the start.

- When adding or removing elements from the array, the


places of all elements after that element change. This
process causes a waste of time.

- When the array is wanted to be sorted, since the elements will be


replaced, the complexity may increase and the working time
will increase.
5

LINKED LISTS
- Lists that do not have consecutive elements in memorylinked
list is called.

- Inlinked lists, each element holds the location of the next


element. The location of the first element is held in a
pointer of type struct. Thus, all elements of the linked list
can be accessed.

- Each element of a linked list array is a struct object. While some


members of this structure object hold the values of the linked list
elements or other information they will carry, one member holds
the address information of the structure object, which is the next
linked list element.
6

LINKED LISTS
- Linked list structures are similar to two-dimensional
array structures. It also has the properties of a one-
dimensional array.

- In this data structure, as in one-dimensional arrays, the deleted data


fields are still in the list, and the length of the list is not shortened even
though the data is deleted.

- It is necessary to increase the capacity when the size of the


list is not enough for adding elements. In this case, a new
data structure is needed so that the size can be increased
at any time and the size of the list automatically decreases
when the element is removed.
7

LINKED LISTS
- Thereis no dynamic approach to linear data structures.
When requested, memory space cannot be taken or
available memory space cannot be returned. Linked lists
are dynamic data structures and allow the above
operations to be performed. Memory sizes called nodes
are used in linked lists.

- Linked lists are used in several types;


- One-way linear linked list
- bidirectional linear linked list
- One-way circular linked list
- bidirectional circular linked list
8

LINKED LISTS
- Comparing Linked Lists and Arrays:
- Series;
- Resize is difficult
- Adding a new element is difficult
- Deleting an element is difficult

- All the elements of the array are allocated memory space.

- These problems can be solved with linked lists.

Mahmut 0

Mehmet one

Angel 2nd
text Murat 3

Mustafa 4

5
9

LINKED LISTS

- Also, in linked lists


-A separate memory area is allocated for each element.

- Information is conceptually sequential, but its


memory location is not sequential.
- Each element (node) represents the next.
10

LINKED LISTS
- Example: Linked list structure in C language
struct ListNode
{ int data;
struct ListNode *next;
}
- Theaddress of the first element of the linked list global can be kept in a
pointer. If the pointer to the last element isNULL left as the address.
Linked list elementsmalloc It is created by dynamic memory functions
such as

- Example: Linked list structure in Java


languagepublic class ListNode
{
int data;
public ListNode next;
}
11th

LINKED LISTS

- lists;
- Each element in the list data (data) and link (link) part.
It refers to the information stored in the data part.
The link part points to the next element.

public class ListNode


{
Address
int data;
public ListNode next; } Data link

Structure of a node
12

LINKED LISTS

-A start in the list (head) element (indicates


the beginning of the list and must start with
this node to reach other nodes), and the last
(tail) staff.
- active in the list (current) element is the element whose information
we can access at the moment.

current

a single element tail


head
13

Linked List Operations


- Operations with lists,
- Adding an element to the list
- top
- end
- In-line
- Deleting an element from the list
- all over again

- from the end


- All of them
- The element with the specified information
- Element in the desired sequence
- Call
- Listing
- According to the requested information

- Control
- empty list
- List size
14

One Way Linked Lists

- There
is only one link between the elements in the list. In
such linked lists, the direction of movement is only
from the beginning to the end of the list.

tail
head
15

Adding Elements to the Head of a One-Way Linked List

8 8 one 2nd 3

Head A one B 3 NS3 F0


x=5
D Let's add the element
5 one 2nd 3

Head A1 B 3 NS3 F0

x=5
D8
16

One Way Linked List Prepending


Start

new=null
first = null

Workman
TO TO
my node new=new my node()
will be added first=null first = new
new.data
me?

H
H

Finish it new.later=first
first=new
17

One Way Linked Lists

- class Loop - class Blist


- { - { private Loop first, last;
- public int data; - // Holds the address of the first node of the list

- // can be reproduced in different types - public BList()


- public Loop tail; - // When a BList object is created

- // address of the last - { first = null;


- // opens as an empty list.
- nodepublic void print()
- }
- {System.out.print(" "+data); }
- public void Add Basa(int data)
-
- // adds elements per list
- }
- {
- Loop new = new Loop();
- //for C# Console.WriteLine(" "+data);
- new.data = data;
- new.queue = first;
- first = new;
- }
18

Ending a One-Way Linked List


8 one 2nd 3

Head A one B 2nd NS3 F0

x=9
G

8 one 2nd 3 9

Head A one B2 C4 F9 G 0
19

One Way Linked List Ending

Start

new=null
first = null

end=null

Workman
TO TO new.queue=null
my node new=new my node()
will be added first=null first = new
new.data
me? last=new

H
H
new.queue=null
Finish it
last.queue=new
last=new
20

One Way Linked Lists

- public void add to end(int data)//


- Adds an element to the end of the list
- { Loop new = new Loop();
- new.data = data;
- new.queue = null;if
- (first == null) {
-
- first = new;
- last = new;
- }
- else
- { last.queue=new;
- last = new;
- }
- }
21

One-Way Linked List-Insertion


8 one 2nd 3

Head A one B 2nd NS3 F 0

x=4
TO
8 one 2nd 3

Head A one B 2nd NS4 F 0

E3
22

One-Way Linked List Interleaving


Start

new=null
first = null

active=null

Workman
TO TO new.queue=null
my node new=new my node()
will be added first=null first = new
new.data
me? active=new

H
H

Finish it

new.data > active.data H


(new.data < active.data) active=active.queue

TO
new.queue=active.queue
active.queue=new
first=active
23

Removing Elements from a One Way Linked List

8 one 2nd 3

Head A one B 2nd NS3 F0

removing the C element

one 2nd 3

Head A1 B 3 NS3 F0

.
24

One Way Linked Listing - Listing

Start

list=first

Workman
H
list.data
elixlteen=encuelkl list=list.queue
me?

TO

Finish it
25

One Way Linked List- Search

Start

search=first

Workman
H H
chargecellk
with aa=nneu search.data=x search=search.queue

me?

TO TO

Finish it
26

One Way Linked List - Delete


Start

delete=first

previous=first

erai=nx
sEill.evm
H
previous=delete
will add
delete=delete.queue
=ni?ull
delete

TO
TO
delete=null
Not found

TO
delete=first first=first.queue Finish it

H
previous.queue = delete.queue
27

Two Way Linked Lists:


- Thereis a two-way link between the elements in the list. There are two
pointers in the element's connection information section. One of this
pointer holds the element that comes after it, and the other holds the
address information of the element that comes before it.

- Inthis way, it is possible to move both from the beginning to


the end of the list and from the end of the list to the
beginning. Since this method has a more flexible structure, it
can be more functional in solving some problems. Example:
Phone book, Remote control channel list

tail
head
28

Adding a Bidirectional Linked List

Start

new=null
first = null

end=null

Workman
TO TO new.then=null
my node new=new my node()
will be added first=null first = new
new.data
me? last=new

H
H
new.then=null
Finish it last.later=new
new.once=last
last=new
29

Bidirectional Linked Lists: Adding Elements


List Top (head) End of List (tail)
one 2nd 3 4 5

0A2 oneB 3 2nd


D 4 3 TO5 4F0

Adding element C: The place to insert C is found and a C node is created.

LB WORK

one 2nd 3 4 5

0A 2nd one
B 6 6 D 4 3 TO5 4 F0

2C3
30

Bidirectional Linked Lists: Element Deletion

List Top (head) End of List (tail)


one 2nd 3 4 5

0A2 oneB 3 2nd


D 4 3 TO5 4F0

Deleting element D: D's location is found and the link is updated.

WORK
LB

one 2nd 3 4 5

0A 2nd oneB 4 2nd


D 4 2ndTO 5 4 F0
31

Two Way Linked Listing

Start

list=first

Workman
H
list.data
elixlteen=encuelkl list=list.then
me?

TO

Finish it
32

Two Way Linked List Deletion


Start

delete=first

erai=nx
sEill.evm
H
will add delete=delete.then

=ni?ull
delete

TO
TO
delete=null
Not found

TO first.after.once=null
delete=first first=first.later Finish it

H
delete.once.later=delete.then

delete.then.once=delete.once
33

Circular Linked Lists:


- One-Way Circular Linked Lists : There is a one-way link between the
elements in the list. The only difference from unidirectional linked lists is
that the pointer of the last element shows the address of the first element
of the first list. In this way, if we know the address of one of the elements in
the list, we can access all the elements in the list.
active
tail

- Bidirectional Circular Linked Lists : They are lists with both circularity
and double dependency properties. The node before the first node is
the last, and the node after the last node is the first.
active
tail
34

Linked List Example in Java Programming Language:


Node Structure of Linked List

- class Node
-{
- public int data; // can be reproduced in different types

- public node next; // Address of the next nodepublic Node(int


- incomingData) // constructor method{ data = incomingData; }//
- Passes its value while creating the nodepublic void print() //
- Prints the data of the node{ System.out.print(" "+data); }
-
-}
-
35

Java-Linked List and Attachment Structure in


Linked List
- class BLlist
-{
- private Node bass; // Holds the address of the first node of the
- public BList() list // When a BList object is created
- {
- bas = null; // opens as an empty list.
- end=null;
- }

- public void add basa(int newElement) // Adds an element to a list link


- {
- Dugum newDugum = new
- Dugum(newElement); newdug.next = press;
- bas = newfound;
- }
36

Java-Linked List and Attachment Structure in


Linked List
- public void Add to End(int newElement) // Adds an element to a list link
- {
- Dugum new = new Dugum(newElement);
- new. next = null;
- if (first == null) {
-
- first = new;
- last = new;
- }
- else
- { end. next=new;
- last = new;
- }

- }
37

Java-Linked List Lookup Structure

- find public node(int key) {


- //Finds key value in list
- Node active = press;
- while(active.data != key) {
-
- if(active.next==null)
- return null;
- else
- active = active.next;
- };
- return enabled; }
38

Delete Structure in Java-Linked List


- public Delete node(int key)
- {
- // Deletes the node with the given key value
- Node active = bas;
- node previous = press;
- while(active.data!=key) {
-
- if(active.next==null) else { return
previous = active;
null;
- active = active.next; }
- }
- if(active==press) bass = press.next;
- else previous.next = active.next;
- return enabled;
- }
39

Java - List Structure in Linked List


- public void list()
-{
- System.out.println();

- System.out.print("List from start to finish: ");


- Node active = press;
- while(enabled!=null)
- { active.print(); active=enable.next; } }
-
- }
40

Java - Linked List Example


- // The class that tests the Bliste and Dugum classes with their methods by creating a
linked list

- class BListTest {
- public static void main(String args[]) {
- BList list = new BList(); // creates a linked list object named list. Add
- to list.base(9);
- for(int i=8; i>=1; --i) add to list.basa(i); //add to list.end(i);
- list.list(); int value = 5; Node d = list.find(value);
- if(d==null) System.out.println("\n"+value+" Not in List");
- else System.out.println("\n"+value+" Found"); node
- s = list.delete(5);
- list.list(); Screen Output:
- } // End-to-end List: 1 2 3 4 5 6 7 8 9 // 5
- } Found
// End-to-end List: 1 2 3 4 6 7 8 9
41

Linked List Example and Usage in Java


Programming Language
- Homework:

- In the given example


- Adding,
- Adding from scratch
- Add in desired order
- Penultimate structures
- Deletion

- erasing over
- Delete in desired order
- end deletion
- structures will be created by you on this example and
delivered to the lecturer.
42

Homework

- 2nd-
- Show the number and letter averages of N students for K courses with
connected sequences.
- Each node will contain the student number, the code of the course, and the
letter average of the course.
- Each student's number will be the information in the headNode. The code

- for each lesson will be the information in the headNode.

- Each node will display the next student in the same course. Each
- node will show the other course of the same person.
- The program will be prepared as Java or C# Windows application and will do the following
operations with the buttons.
- 1- Adding a new lesson to a student 2-
- Adding a new student to a lesson 3-
- Deleting a lesson of a student 4-
- Deleting a student from a lesson
- 5- Listing all the students in a course in order of numbers 6- Listing all the
- courses a student has taken in order according to the course code
43

Homework

- 3- Implement circular linked list with Java or


C#.
- Adding,
- Adding from scratch
- Add in desired order
- Penultimate structures
- Deletion

- erasing over
- Delete in desired order
- end deletion
Valiant

(stack)

44
45

Stack/Stack
- Lastin, first out (Last In First Out - LIFO) or First in, last out(
First-in-Last-out FILO) works with logic.

- Thedata structure in which element additions are made from


the top (top) is called stack.

- Whenan element is added, it is placed at the top of the stack. When


removing an element, the top element of the stack is removed.

- Thiselement is the last element added in the stack. For this


reason, stacks are also called LIFO (Last In First Out) lists.
46

Stack/Stack
- There are 2 ways to perform the stack structure.
- Using an array
- Using a linked list

- empty stack: empty stack


- push (put):Adding elements to the stack.

- pop (take):Removing an element from the stack


47

Stack Operations
- Main stack operations:
- push(object): adds a new object
- Entry: Article Output: No
- pop(): Removes and returns the most recently added object.
- Entry: No Output: Article

- Auxiliary stack operations:


- ball(): Returns the most recently added object without removing it.
- Entry:
No Output: Article
- to you(): Returns the number of stored objects.
- Entry: No Output: Integer
- isEmpty( ): returns whether there is an object in the stack or not.
- Entry: No Output: boolean
48

Stack Structure
push(3);
push(2); push(11);
push(12); 12 push(5);
pop();

12 2nd 5
2nd 3 11th
3 2nd
3

Stack stack stack stack


49

Stack/Stack
- Example uses
- Undo operations in software applications are done with
stack. LIFO structure is used for Undo operation.
- TheBack button (to previous page) in web browsers uses
stack. Here, the LIFO structure is used.
- Stack
can be used for operators (such as +,*,/,-) and
operands in mathematical operations.
- Stack can be used to check parentheses in spell
check.
50

Stack/Stack
- Example: Adding and removing from the stack

- Process stack (hill) Output


- push(“M”); M
- push(“A”); MA
- push(“L”); GOODS
- push(“T”); MALT
- pop(); GOODS T
- push(“E”); MALE T
- pop(); GOODS TE
- push(“P”); MALP TE
- pop(); GOODS TOE
- push(“E”); MALE TOE
- pop(); GOODS TOP
51

Array-Based Stack
- Theeasiest way to implement a stack is to use
an array. The stack structure can be made to
hold a maximum of N elements on the array.
12

12 2nd 11th
2nd 3 2nd
3 3

pop(); push(11);
52

Array-Based Stack
- We add objects from left to
right. A variable follows the
index of the topmost
object. Workman
This index value is taken when
extracting.
53

Array-Based Stack
- The array in which the stack objects are stored

may become full. In this case, the push

operation gives the following message.

- FullStackException
(FullStackException)
- This is the limitation of the array-
based approach.
54

Performance and Limitations


- my achievement

-n Let be the number of objects in the stack

- used area Front)


- Each transaction O(1) takes place in time.
- Limitations
- The top number of the stack must be predefined and
cannot be changed.
- Attempting to add a new object to a full stack
may cause exceptions.
55

Growable Array-Based Stack Approach


- push If the array is full during operation,
the array holding the stack is replaced
with a larger array, rather than
returning an exception notification.
- How big should the new array
be?
- Incremental strategy: heap size is
fixed NS is increased by its value.
- Doubling strategy: the
previous array size is doubled
- It is helpful to avoid such problems
by performing the stack operation
using linked list structures.
56

Stack and Operations


public class Stack {

int capacity=100; // maximum number of elementsint NS[];


//Stack elements – positive integerint p; // number of
elements

public Stack(){ // constructor procedure


s[] = new int[capacity]; p = 0;

int Bay(int item); int


get();
int top();
boolean is it empty();
boolean refill();
}
57

Stack Operations – bosmu, refill

// return true if stack is empty


public boolean empty() {
if (p < 1) return true; else
return false;
} //done-bosmu

// Return true if the stack is full


public boolean fill(){
if (p == capacity-1) return true; else return
false;
} // done-fill
58

Stack Operations: put


// Put an element on the stack again
// Returns 0 if successful, -1 if unsuccessful.put int(int
new){

if (fill()){
// The stack is full. New elements cannot be
added.return -1;
}

S[p] = new;
p++;

return 0;
} /done-put
59

Stack Operations: top


// Returns the number at the top of the stack //
Returns -1 if the stack is empty
public int top(){
if (bosmu()){
// Returns an error if the stack is up
System.out.println("Stack underflow"); return
-1;
}

return S[p-1];
}
Translated from Turkish to English - www.onlinedoctranslator.com

60

Stack Operations: get


// Returns the top element. //
Returns -1 if the stack is empty.
public int get(){
if (bosmu()){
// Returns an error if the stack is empty
System.out.println(“Stack underflow”); return
-1;
}

int id = p-1; // location of the top elementp--;


// delete element

return S[id];
}
61

Stack Usage Example


public static void main(String[] args){
Stack y = new Stack();

if (y.bosmu())
System.out.println("The stack is empty");

y.put(49); y.koy(23);

System.out.println(“First element of the stack: ”+ y.al());

y.koy(44); y.koy(22);

System.out.println(“First element of the stack: ”+ y.al());


System.out.println(“First element of the stack: ”+ y.al());
System.out.println(“First element of the stack: ”+ y.ust());
System.out.println(“First element of the stack: ”+ y.al());.

if (y.bosmu()) System.out.println(“Stack is empty”);


}
62

Stack-Linked List Implementation


Top
9 2nd 6 15
Initial state

put(3)
Top
3 9 2nd 6 15 After adding 3

get()

Top
9 2nd 6 15 3 after receiving

get()

Top
2nd 6 15 after 9 received
63

Linked List Implementation


public class YiginDugumu {
int element;
YiginDugumu next;

My Worship(int) to){
element = e; next = NULL;
}
}

public class Stack {


private StackNode top;

public Stack() {ust = null;}

void Bay(int element);


int get();
int top();
boolean is it empty();
};
64

Stack Operations: bay, bosmu

// Add new element to stackpublic


void put(int element){
StackNode x = new StackNode(element);
x.next = top;
top = x;
}

// Return true if the stack is


emptypublic boolean empty(){
if (ust == NULL)
return true;
else
return false;
}
65

Stack Operations: top

// Return the first element of the stack


public int top(){
if (bosmu()){
System.out.println(“Stack underflow”); // Empty stackreturn -1;
// Mistake
}

return master.element;
} //done-top
66

Stack Operations: Get()


// Deletes and returns the topmost element of the stack.
public int Get(){
if (bosmu()){
System.out.println(“Stack underflow”); // Empty stack.return -1; //
Mistake
}

YiginDugumu temp = top;

// skip to the next elementtop =


top.next;

return temp.element;
} //do-get
67

Stack Usage Example


public static void main(String[] args){
Stack y = new Stack();

if (y.bosmu())
System.out.println("The stack is empty");

y.put(49); y.koy(23);

System.out.println(“First element of the stack: ”+ y.al());


y.koy(44); y.koy(22);

System.out.println(“First element of the stack: ”+ y.al());


System.out.println(“First element of the stack: ”+ y.al());
System.out.println(“First element of the stack: ”+ y.ust());
System.out.println(“First element of the stack: ”+ y.al());.

if (y.bosmu()) System.out.println(“Stack is empty”);


}
68

Examples –Java
- There is also a ready-made Stack class in Java. In the
example below, the StringsNS placed on the stack and
listed in reverse order.
- import java.util.*;

- public class StackTest

- {
- public static void main(String args[])

- { String str[] = { "Computer", "Cabinet", "Desk", "Chair", "Row" };


- Stack s = new Stack();for(int i=0; i < t.length; ++)

- s.push(str[i]);
while(!s.empty() ) System.out.println(s.pop());

- }
- }
69

Practice Assignment
- Compilers/word processors
- If we think about compilers, they check whether the
parentheses in the expression we write are the same.
- For example: The expression 2*(i + 5*(7 – j / (4 * k)) lacks
parentheses. ")"
- Write a program that checks if the expression has an
even number of parentheses using the stack.
70

Practice Assignment

- Checking the brackets using the stack:


one) Create an empty stack and start reading symbols
2nd) If the symbol is the start symbol ( '(', '[', '{' ) put in stack
3) If the symbol is the closing symbol ( ')', ']', '}' )
NS. Return error report if stack is empty
II. if not
get from stack

Send an error if the received symbol and the start


symbol are not the same
4) Return an error if the statement is finished and the stack is full.
71

EXAMPLES
72

Examples- C++
- Example 1: One-way linked list
- #include <stdio.h>
- #include <stdlib.h>
- main() {
- struct notes {
- int visa1;
- struct notes *bag;
-} *newaddress, *first, *last;
- newaddress=(struct notes*) malloc(sizeof(struct notes));
- printf("Newaddress:%d\n",newaddress);
- first=newaddress;

- end=newaddress;

- newaddress->visa1=79;
- newaddress->bag=NULL;
73

C++
- printf("first:%d\n",first); //Holds the address of the first element

- printf("end:%d\n",end); //Holds the address of the last element

- printf("T1___newaddress->visa1:%d newaddress->bag:%d\n",newaddress->visa1,
newaddress->bag);
- //Request place from memory

- newaddress=(struct notes*) malloc(sizeof(struct notes));


- printf("Newaddress:%d\n",newaddress);
- end->bag=new address;

- newaddress->visa1=95;
- newaddress->bag=NULL;

- end=newaddress;

- printf("first:%d\n",first);
- printf("end:%d\n",final);
- printf("T2___newaddress->visa1:%d newaddress->bag:%d\n", newaddress->visa1,
newaddress->bag);}
74

LINKED LISTS
- Requesting a new address from memory on first operation
new
new

first 7332 Visa=79 bag= NULL

end
75

LINKED LISTS
- Requesting a new address from memory in the second operation

new

7344 Visa=95 bag= NULL


76

LINKED LISTS

new new

first (bass) Visa=79 end(queue) first (bass) Visa=95 end(queue)

7332

7344 0
77

C++
78

Examples - C++
- Example: 2- Storing movie names with bidirectional linked list

- # include <stdio.h>
- # include <stdlib.h>
- # include <string.h>
- # define TSIZE 45
- struct film {
- char title[TSIZE];
- int rating;
- struct film * next, * previous; } ;
- int main(void) {
- struct filim * first = NULL;
- struct film * current, *last;
- char input[TSIZE];
- puts("Enter the title of the movie (enter (space) to end):");
79

C++
- while (gets(input) != NULL && input[0] != '\0') {
- now = (struct film *) malloc(sizeof(struct film)); if
- (first == NULL) first = current;
- else {last->next = current; current->previous=last;}
-

- current->next = NULL;
- strcpy(current->title, input);
- puts("Enter rating <0-10>:");
- scanf("%d", ¤t->rating);
- while(getchar() != '\n') continue;
- puts("Enter the title of the movie (enter a space to end):"); last
- = current;
- }
80

C++

- if (first == NULL)
- printf("Data is not entered.");
- else
- printf("Movie List:\n");
- current = first;
- while (current != NULL) {
-
- printf("Movie: %s Rating: %d\n", current->title, current->rating);
- current = current->next;
- }
- current = first;
- }
81

LISTS and AFFILIATE LISTS

present

first 8164 next=0


82

LISTS and AFFILIATE LISTS

present present

first 8164 next previous 12272 next=0


83

LISTS and LINKED LISTS


Examples
84

Linked List Example in C# Programming Language and


Usage-ONE WAY LINKED LIST Node Structure
- public class ListNode
- {
- public string number, nameSurname;
- public double mean;
- public ListNode next;
- public ListNode(string number, string firstname, double mean) {
-
- this.number = number; ;
- this.nameSurname = firstname;
- this.average = mean;
- }
- }
85

C# - ONE WAY LINKED LIST Structure


- public class LinkedList {
-
- public ListNode headNode, tailNode;
- public LinkedList()
- {
- headNode = new ListNode("head","",o);
- tailNode = new ListNode("tail","",o);
- headNode.next = tailNode;
- tailNode.next = tailNode; }
-
- }
86

C# - ONE WAY LINKED LIST


Node Insertion

- public void Add(LinkedList bL, ListNode lN, string place)


- { ListNode active = bL.headNode;
- if (place == "BASE" )
- { lN.next = active.next;
- active.next = lN; }
- else if (place == "ROW" ) {
-
- while ((active.next!= bL.tailNode) && (string.Compare(active.next.number, lN.number)<0))
- active = active.next;
- lN.next = active.next;
- active.next = lN;
- }}
- else if (place == "END" )
- { while (active.next != bL.tailNode)
- active = active.next;
- lN.next = active.next;
- active.next = lN;
- }}
87

C# - ONE WAY LINKED LIST


Node Delete

- //Deleting a node from scratch

- if (rBBas.Checked)
- connectedListe.headNode.next = connectedList.headNode.next.next;

- //Deleting an End Node


- else if (rBSon.Checked)
-{
- ListNode active = connectedListe.headNode;
- while (active.next.next != connectedList.tailNode)
- active = active.next;
- active.next = linkedList.tailNode;
-}
88

C# - ONE WAY LINKED LIST


Node Delete
- //Delete All
- else if (rBTum.Checked)
-{
- ListNode active = connectedListe.headNode;
- while (active.next != connectedList.tailNode)
- active.next = active.next.next;
-}
- //Deleting the called contact

- else if (rBKisi.Checked)
-{
- ListNode active = connectedListe.headNode;
- while((active.next!=connectedList.tailNode) &&(active.next.number!=tBNum.Text))
- active = active.next;
- active.next = active.next.next;
-}
89

C# - ONE WAY LINKED LIST


Node Delete
- //Deletion in Desired Order
- else if (rBSira.Checked)
-{ int Order = Convert.ToInt16(tBSil.Text); if int i = 1;
- (Order != 0)
- { ListNode active = connectedListe.headNode;
- while ((active.next != connectedList.tailNode) && (i < Row))
- { active = active.next; i++; }

- if ((active.next == connectedList.tailNode) && ((i‐1) < Row)) MessageBox.Show("A


- value greater than the number of items in the list was entered !",
- "Error !", MessageBoxButtons.OK);
- else if (!(active.next == connectedList.tailNode))
- { active.next = active.next.next; }
- }
-}
90

BI-WAY in C# Programming Language


LINK LIST
- TWO-WAY LINK LIST
- public class ListNode
- { public string firstname;
- public ListNode previous, next;
- public ListNode(string firstName)
- { this.nameLastName =
- firstName; } }
- public class LinkedList {
- public ListNode headNode, tailNode;
- public LinkedList()
- {
- headNode = new ListNode("head");
- tailNode = new ListNode("tail");
- headNode.previous = headNode;
- headNode.next = tailNode;
- tailNode.previous = headNode;
- tailNode.next = tailNode;
- }
- }
91

Linked List Example and Usage in C#


Programming Language

- Adding an element
- ListNode newNode = new ListNode(“Mustafa");
- newNode.next = active.next;
- active.next.previous = newNode;
- active.next = newNode;
- newNode.previous = active;
92

Linked List Example and Usage in C#


Programming Language

- Delete an element
- while ((active.next != connectedList.tailNode) && (active.next != to be deletedNode)) {
-
- active = active.next;
- }
- active.next.next.previous = active;
- active.next = active.next.next;
93

Linked List Example and Usage in C#


Programming Language

- Element search
- while ((active.next != connectedList.tailNode) && (active.next != searchedNode))
- { active = active.next;}
- while ((active.previous != connectedList.headNode) && (active.previous != searchedNode)) { active
- = active.previous; }
94

Bidirectional Linked List-Queue in C# Programming Language

- class Node
- {
- public object data; // data to be kept in the node
- public Node previous, next; // Node's address information
- public Node(object data)
- {
- this.data = data;
- this.previous = null;
- this.next = null;
- }
- }
- public class BList
- {
- Node firstNode = new Node(“”);
- Node sonNode = new Node(“”);
- public int s = 0;
- public BList() // Linked list structure is set {
-
- this.firstNode.next = this.sonNode;
- this.sonNode.previous = this.firstNode;
95

Bidirectional Linked List-stack in C# Programming Language

- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Collections;
- namespace ConsoleApplication1_4.WEEK {
-
- class Node
- {
- public object data; // data to be kept in the node
- public Node previous, next; // Node's address information
- public Node(object data)
- {
- this.data = data;
- this.previous = null;
- this.next = null;
- }
- }
- public class BList
- {
96

Bidirectional Circular Linked List in Java Programming


Language

- class Node {
-
- object data;
- Node prev;
- node next;
-
- public Node( Object data ) {
- this.data = data;
- }
-
- public Node( Object data, Node prev, Node next ) {
- this.data = data;
- this.prev = prev;
- this.next = next;
- }
- }
-
- public class CircularDoublyLinkedList {
-
97

Examples - C++
- Example:- Bidirectional linked list

-
# include <stdio.h>
# include <stdlib.h>
# include <conio.h>
# include <string.h>

typedef struct person


{
char name[50];struct
person *after;
/* This pointer will be assigned the address that will constantly point to the next struct.
In this way, each struct will know where the next struct
is in memory*/
struct person *once;
/* This pointer will be assigned the address that will constantly point to the previous struct.
In this way, each struct will know where the previous
struct is in memory*/
};

struct person *new , *first , *last;/* We made new, first and last name definitions in the struct person type.*/

void menu(); void word_add(); void list(); void deletion();

/*Gulnur CAKIR*/
98

Examples - C++
- int main()
{
new=NULL; first=NULL; end=NULL; /* We made all structs NULL */

menu();/*We call the menu function*/


getch();
return 0;
}
/****************************/ /
*Menu*/
void menu()
{
system("cls");/*Screen clearing function*/int
reply;
printf("\n\n\n\n\t\t1-Add record\n");
printf("\t\t2-List records\n");printf(
"\t\t3-Unregister\n");printf("\t\t4-Exit\n"
);printf("\t\tPlease make your choice :");
scanf("%D",&reply);switch(reply)

{
case one : myname_add(); break;
case 2nd : list(); break;case 3 :
delete(); break;case 4 : exit(one);
break;

}
99

Examples - C++
- /* Add Node Function */void
word_add()
{
if(first==NULL)/* Is there an employee in my home?*/{
/* If there is no element in my case, first=NULL.*/
struct contact *new = ((person *) malloc(sizeof(person))); /*We have just defined the struct person type and the size of the struct from memory
how far we got */
printf("\n\tPlease enter the name of the person : ");scanf("%NS",&new-
>name);/*New information received from user*/new->then=NULL;
/* NULL since there is no element after newly received information */
first=new; last=new; /* The new and last policy is synchronized since it is the first element retrieved for the node*/
}
else
{
struct contact *new = ((person *) malloc(sizeof(person)));
- /* We just defined the struct as the person type and took up memory space as much as the size of the
struct */printf("\n\tPlease enter the name of the person : ");scanf("%NS",&new->name);/*New
information received from user*/new->then=NULL;
/* NULL because there is no element after the newly received information */ /*
last->after=new; The pointer of a previous struct named after is set to the new one*/
new->once=last; / *The only difference is from creating a one-way linked list*/
/* The pointer of the currently created struct named once is synchronized to the previous struct*/
last=new;
/* The struct named last is now its new struct. The purpose of doing this when a new node will be added
knowing which struct was added last
Equalizing the last added struct to the new struct, making it equal the pointer named once of the newly created struct
to the end.*/
}
printf("\n\tPress any key to return to the main menu...");
getch();
menu();
}
one hundred

Examples - C++
- /*Record listing*/void list()/* Same as listing a one-way
linked list*/{

struct contact *call;


/* We defined a type named intermediate in the struct person type */
printf("\n\n");
/* equate the intermediate struct to the first struct and move through the node until we
see NULL*/
for(search=first;search!=NULL;search=search->after) {

printf("\t\t->%s\n",search->name);

}
printf("\n\tPress any key to return to the main menu...");
getch();
menu();

}
/***********************************/
101

Examples - C++
- /*Delete record*/
void deletion()
{ char name[20]; struct contact *delete;

printf("\n\tEnter the name you want to delete."); scanf("%NS",&name);


delete=first;
while(delete)

{ if(!strcmp(name,delete->name))/*If the searched name is found in my node*/


break;
delete=delete->then;

}
if(clear==NULL)
printf("\tNot Found.\n");else
if(delete==first)
{ first->after->once=NULL;free first=first->then;
(delete); printf("\tRecord deleted.");
}
else if(delete==end)
{ last=delete->before; delete->once->then=NULL;
free(delete); printf("\tRecord deleted.");
}
else
{ delete->once->then=delete->next;
delete->then->once=delete->once;
free(delete); printf("\tRecord deleted.");
}
printf("\n\tPress any key to return to the main
menu...");getch(); menu();
}
102

Game with C++ Circular Linked Lists

- # include "stdio.h"
- # include "conio.h"
- # include "stdlib.h"
- # include "string.h"
- # include "iostream.h"
- //NAME OF THE PLAYERS---------------------------------------------- -------------------
- char *names[10]= {"HACER","GULTEN","IDRIS", "HASAN","HATICE",
"CEMIL","BELMA", "CANSU","EBRU","NALAN"};
- //------------------------------------------------ -------------------------------------------
- typedef struct data{
- char name[20];
- struct data *back;
- } BLISTE;
- BLISTE

- *first=NULL,*last=NULL; //------------------------------------------------ ------


103

Examples-Play with Circular Linked Lists


- add int(BLISTE *number arrived) {

-
- if(first==NULL)
- {
- first=number arrived;

- last=first;
- first->back=first;

- }
- else
- {
- last->back=numbers arrived;

- end=numbers arrived;

- last->back=first;
- }
- return 0;
- }
- //------------------------------------------------ -----------------------------
104

Examples-Play with Circular Linked Lists


- int players()
- { BLISTE *p; int x=3,y=3,i=0; clrscr();
- gotoxy(x,y);printf("CIRCULAR LINK LIST");y+=2;
- gotoxy(x,y);printf("TOGETHER SUBJECT: Designing a Game Using the
Circular Linked List Structure");

- y+=3; gotoxy(x,y);printf("Players : "); p=first;


- while(p->back!=first) { printf("%s\n ",p->name); p=p->back; i++; }
- printf("%s\n ",p->name);

- y+=13;
- gotoxy(x,y);printf("TOTAL NUMBER OF PLAYERS: %d ",i); getch();
- return 0;}

- //------------------------------------------------ ----------------------------
105

Examples-Play with Circular Linked Lists

- int game_at(BLISTE *previous,BLISTE *to be deleted)


- { if(first->back==first) { //if there is an element in the list
- clrscr();
- printf("There is only 1 person in the game right
- now"); printf("GAME WINNER = %s",first->name); }
- else if(previous->back==first) //first element to delete?
- { previous->back=first->back; first=first->back;
- printf(" Quitting Game....%s",previous->name);
- free(to be deleted); players(); }
- else if(to be deleted==last)//last element to be deleted?
- { previous->back=first; last=previous; free(to be deleted); players(); }
- else // will it be deleted? { previous->back=to be deleted->back; free(to
- be deleted); players(); }
- return 0;}
- //------------------------------------------------ ---------------------------------------------
106

Examples-Play with Circular Linked Lists

- void main(void) {
- clrscr(); randomize();
- BLISTE *new;int i,x=3,y=3;
- for( i=0;i<10;i++) {
- new=(BLISTE *)malloc(sizeof(BLISTE));
- if(!new) { clrscr();
- printf("Sorry, there is not enough free space to add players"); exit(0); }
-
- else { strcpy(new->name,names[i]); add(new); }
- }
- clrscr();x=3;y=3; int
- originating; players();
- new=first; BLISTE *p; BLISTE *previous;
107

Examples-Play with Circular Linked Lists


- do {
- printf("\n\nMY :%s ---> Can you give a number? ",first-
- >name); scanf("%d","ed);
- for(i=0;i<said;i++) { new-
- >name; previous=new; new=new->back; }
- //to be disconnected.. address=new, the address of the previous one will make the
guess the person addressed with p
- p=new->rear;//who will guess the
- number_kick(previous,new); new=p;
- } while(first!=last);
- if(first==last) { clrscr(); x=5; y=5;
- gotoxy(x,y); printf("There is only 1 person in the game right now");
- gotoxy(x,y);printf("GAME WINNER = %s",first->name); y+=2;
- gotoxy(x,y);printf("Game over...press any key to end the
program."); y+=2; getch(); exit(0); }
- getch(); }
108

Examples -Java
- Example: Creating and using a string class using arrays in
Java.
- import java.io.*;
- class StackChar
- {
- private int maxSize; private char[] stackArray; private int top;
- public StackChar(int max)
- { maxSize = max; stackArray = new char[maxSize]; top= -1; }

- public void push(char j) { stackArray[++top] = j; }

- public char pop() { return stackArray[top--]; }

- public boolean isEmpty() { return top==-1; }}


-
109

Examples –Java

- class Reverse
-{
- public static void main(String args[]) {
-
- StackChar y = new StackChar(100);
- String str = "Hello";
- for(int i=0; i<str.length(); ++i)
- y.push(str.charAt(i));
- while(! y.isEmpty() ) System.out.println(y.pop());
- }
-}
110

Examples –C#
- Sample: Stacking with linked list
- class stackNodeC
-{
- public string bookName; public stackNodeC next;
- public stackNodeC(string bookName) { this.bookName = bookName; }
-}

- class stackC
-{
- public stackNodeC headNode;
- public stackC(string bookName)
-{
- this.headNode = new stackNodeC(bookName);
- this.headNode.next = headNode;
-}
-}
- stackC bookYigin = new stackC("");
-
111

Examples –C#

- /* Stack operations:
- empty stack stackSize() == 0 number of elements = stackSize()
- add element = push(bookName) get elements = pop() */

- public int stackSize()


-{
- stackNodeC active = new stackNodeC("");
- active = bookYigin.headNode;
- int i = 0;
- while (active.next != active)
-{
- active = active.next; i++;
-}
- return i;
-}
112

Examples –C#
- // Stack operations (add elements)
- public void push(string bookName) {
-
- if (stackSize() >= MaxSize)
- MessageBox.Show("The heap has the maximum number of elements !

- Cannot add new elements!", "Attention");

- else
- { stackNodeC newNode = new stackNodeC(tBBookName.Text);
- newNode.next = bookYigin.headNode;
- bookYigin.headNode = newNode;
- lStackSize.Text = "Stack Size =
- "+Convert.ToString(stackSize());
- }
- }
113

Examples –C#

- // Stack operations (receiving elements)


- public void pop()
-{
- if (stackSize() == 0)
-{
- MessageBox.Show("There are no elements in the stack!", "Attention");
-}
- else
-{
- bookYigin.headNode = bookYigin.headNode.next;
-}
-}
114

Examples –C++

- Sample: Linked list operations using Stack. Reverse the


entered sentence without breaking the words.
- #include <stdio.h>
- #include <string.h>
- #include <conio.h>
- #include <stdlib.h>
- struct words
-{ char word[50];
- struct words *previous;
-} *top,*recruitment,*spare;
115

Examples –C++

- void push(char *incoming) {


- newelement =(struct words *) malloc(sizeof(struct words));
- strcpy(new element->word, incoming);
- newelement->previous = peak;
- peak = new element; }

- int pop(char *outgoing) {

- if (peak != NULL) {
- spare = peak;
- strcpy(outgoing, vertex->word);
- peak = peak->previous; free(reserve); return 0; }
- else
- return 1; /* stack is empty */
116

Examples –C++

- main() {
- char *rename, *sentence;
- peak = NULL;
-
- printf("Enter sentence: "); gets(sentence);
- newword = strtok(sentence, " "); // do not separate the sentence variable by
space.
-
- while (refresh) {
- push (refresh);
- newword = strtok(NULL, " ");
- }
- newword = (char *) malloc(20); /* newword was NULL, let's make room*/
- while (!pop(renewword)) printf("%s ", newword);
- printf("\n");
- getch();
- }
117

Examples –C++
118

Examples –C++

You might also like