LINKED LISTS.

Slides:



Advertisements
Similar presentations
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Advertisements

Lecture 20 Arrays and Strings
Computer Science 210 Computer Organization Introduction to C.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 15: Linked data structures.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
File IO and command line input CSE 2451 Rong Shi.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Lesson #7 Arrays‏.
CSC 482/582: Computer Security
LINKED LISTS.
Stack and Heap Memory Stack resident variables include:
Lesson #8 Structures Linked Lists Command Line Arguments.
‘C’ Programming Structures and Commands
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Strings CSCI 112: Programming in C.
Computer Science 210 Computer Organization
Linked List :: Basic Concepts
5.13 Recursion Recursive functions Functions that call themselves
Strings (Continued) Chapter 13
A bit of C programming Lecture 3 Uli Raich.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
Lecture 8 String 1. Concept of strings String and pointers
Quiz 11/15/16 – C functions, arrays and strings
Command Line Arguments
A First Book of ANSI C Fourth Edition
CSC215 Lecture Input and Output.
C Basics.
Module 2 Arrays and strings – example programs.
Strings A string is a sequence of characters treated as a group
Programmazione I a.a. 2017/2018.
Computer Science 210 Computer Organization
Arrays in C.
Programming Languages and Paradigms
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Computer Science 210 Computer Organization
LINKED LISTS.
Command-line Arguments
Computer Science 210 Computer Organization
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
Command Line Arguments
C Stuff CS 2308.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
CSE1320 Strings Dr. Sajib Datta
Programming and Data Structure
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
A function with one argument
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Linked List.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Data Structures & Algorithms
C By Example The assumption is that you know Java and need to extend that knowledge so you can program in C. 1. Hello world 2. declarations 3. pass.
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Programming in C Pointers and Arrays.
Strings #include <stdio.h>
Strings …again.
Exam #1 February 23rd (Next Friday)
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Strings Adapted from Dr. Mary Eberlein, UT Austin.
C Characters and Strings
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Files Chapter 8.
Presentation transcript:

LINKED LISTS

Linked Lists A list is a finite sequence, with order taken into account. A linked list consists of ordered nodes like N1, N2, N3,...Nn together with the address of the first node N1. Each node has several fields, one of which is an address field.

Linked Lists The address field of N1 contains the address of N2, the address field of N2, the address of N3, and so on.... The address field of Nn is a NULL address. In the following example, the variable start contains the address of the first node. Each node has two fields, the first contains an integer indicating the position of the node in the list, the second field contains the address of the next node. start 1 2 3

Example of a linked list To declare a linked list, we need to declare a structure where the last component will be a pointer to a variable of the structured type itself. Let's define a list of elephants. Notice that the next component is a pointer to a struct ELEPHANT. The other component store the animal's name and weight. typedef struct ELEPHANT { char name [10]; int weight; struct ELEPHANT* next; }elephant;

Example of a linked list Next, let's declare variables to store our list nodes and the start of the list. /* the nodes - ready to contain 3 elephant names */ elephant eleph1, eleph2, eleph3; /* the start variable - pointer to an elephant node */ elephant* start;

Example of a linked list Let's fill now the elephants' names and weight: strcpy (eleph1.name, "Edna"); strcpy (eleph2.name, "Elmer"); strcpy (eleph3.name, "Eloise"); eleph1.weight = 4500; eleph2.weight = 6000; eleph3.weight = 4750; start eleph1 eleph2 eleph3 "Edna" 4500 "Elmer" 6000 "Eloise" 4500

Example of a linked list Next, let's link all these elephants together and build the linked list. start = &eleph1; eleph1.next = &eleph2; eleph2.next = &eleph3; eleph3.next = NULL; start eleph1 eleph2 eleph3 "Edna" 4500 "Elmer" 6000 "Eloise" 4500

Example of a linked list Finally, let's use our linked list. We will print out the names of all the elephants in it. We will use a a variable p (elephant* p;) as a travelling variable through the list (not unlike the i variable we used to travel though an array). count = 1; /* to count the elephants */ /* the list loop */ for (p = start; p != NULL; p = p->next)‏ { printf ("Elephant #%d is %s.\n", count, p->name); count = count + 1; }

Linked Lists and functions Linked lists can of course be sent to functions. Let's have a function that accepts a list of elephants and returns 1 if an elephant weighing more than 5000kg can be found in the list. int find5000 (elephant* ptr)‏ { int found = 0; for (p = start; p != NULL; p = p->next)‏ if (ptr->weight > 5000)‏ found = 1; return (found); } find5000 (start); would return 1 .

Lists and dynamic allocation So far we knew in advance the number of elephants in the list. But what if we didn't? Let's now have a function named get_elephants that will fill the list from user input. Since we do not know how many elephants the user will enter, we will use dynamic allocation for every node. In the main program, in that case, only the start variable will be declared and all the nodes will be dynamically allocated and filled with values in the function. The function will be called this way: start = get_elephants ( );

Lists and dynamic allocation elephant* get_elephants (void)‏ { elephant *current, *first; int response; /* create first node */ first = (elephant*)calloc(1,sizeof(elephant)); current = first; printf("Elephant name? "); scanf ("%s", current->name); printf("Elephant weight? "); scanf ("%d", &current->weight); printf("\nAdd another? (y=1/n=0)"); scanf ("%d", &response)‏ cont...

Lists and dynamic allocation while (response)‏ /*while response is 1 (yes) */ { /* allocate node and change current pointer */ current->next = (elephant *)calloc (1,sizeof(elephant)); current = current->next; /* fill node */ printf("Elephant name? "); scanf ("%s", current->name); printf("Elephant weight? "); scanf ("%d", &current->weight); printf("\nAdd another? (y=1/n=0)"); scanf ("%d", &response); } cont...

Lists and dynamic allocation current->next = NULL; return (first); } Now can you think how to: Add a node at the end of a linked list? Add a node at the beginning? Insert a node between two nodes? Delete a node? start eleph1 eleph2 eleph3 "Edna" 4500 "Elmer" 6000 "Eloise" 4500

#include <stdio.h> #include <string.h> Creates a linked list to hold four tree names and prints out all the trees in the list. /* This program creates a linked list of tree names. Each node contains the name of the tree and a pointer to the next tree. */ #include <stdio.h> #include <string.h> typedef struct tree { char tree_name [20]; struct tree* next;}tree; int main (void){ /* declaring variables to hold tree nodes */ tree tree1, tree2, tree3, tree4; /* declaring the starting and traveling pointers */ tree *p, *start; /* putting tree names into each node */ strcpy (tree1.tree_name, "Maple"); strcpy (tree2.tree_name, "Fir"); strcpy (tree3.tree_name, "Pine"); strcpy (tree4.tree_name, "Oak");

/* setting the start of the list at tree1 */ start = &tree1; /* linking the other trees together */ tree1.next = &tree2; tree2.next = &tree3; tree3.next = &tree4; /* sets tree4 as the last node of the list */ tree4.next = NULL; /* printing out the list by traveling though it */ p = &tree1; while (p != NULL) { printf ("%s\n", p -> tree_name); p = p -> next; } return (0);

The function checks if a tree name exists in the list of trees from the previous example program. #include <stdio.h> #include <string.h> typedef struct tree { char tree_name [20]; struct tree* next; }tree; int checktree (tree *p, char name[]){ int found = 0; while (p != NULL) { if (strcmp(p -> tree_name, name) == 0) found = 1; p = p -> next; } return (found); int main (void){ /* declaring variables to hold tree nodes */ tree tree1, tree2, tree3, tree4; char treename[20]; /* declaring the starting and traveling pointers */ tree *p, *start; /* putting tree names into each node */ strcpy (tree1.tree_name, "Maple"); strcpy (tree2.tree_name, "Fir"); strcpy (tree3.tree_name, "Pine"); strcpy (tree4.tree_name, "Oak");

/* setting the start of the list at tree1 */ start = &tree1; /* linking the other trees together */ tree1.next = &tree2; tree2.next = &tree3; tree3.next = &tree4; /* sets tree4 as the last node of the list */ tree4.next = NULL; /* checking if a tree is in the list */ printf ("Enter tree name to search: "); gets (treename); if (checktree(start, treename)) printf ("%s was found in our list of trees.\n", treename); else printf ("%s was not found in our list of trees.\n", treename); return (0); }

LINKED LISTS

PLEASE CHECK THE MAIN COURSE PAGE FOR THE NOTES.

#include <stdio.h> #include <string.h> Creates a linked list to hold four tree names and prints out all the trees in the list. /* This program creates a linked list of tree names. Each node contains the name of the tree and a pointer to the next tree. */ #include <stdio.h> #include <string.h> typedef struct tree { char tree_name [20]; struct tree* next;}tree; int main (void){ /* declaring variables to hold tree nodes */ tree tree1, tree2, tree3, tree4; /* declaring the starting and traveling pointers */ tree *p, *start; /* putting tree names into each node */ strcpy (tree1.tree_name, "Maple"); strcpy (tree2.tree_name, "Fir"); strcpy (tree3.tree_name, "Pine"); strcpy (tree4.tree_name, "Oak");

/* setting the start of the list at tree1 */ start = &tree1; /* linking the other trees together */ tree1.next = &tree2; tree2.next = &tree3; tree3.next = &tree4; /* sets tree4 as the last node of the list */ tree4.next = NULL; /* printing out the list by traveling though it */ p = &tree1; while (p != NULL) { printf ("%s\n", p -> tree_name); p = p -> next; } return (0);

The function checks if a tree name exists in the list of trees from the previous example program. #include <stdio.h> #include <string.h> typedef struct tree { char tree_name [20]; struct tree* next; }tree; int checktree (tree *p, char name[]){ int found = 0; while (p != NULL) { if (strcmp(p -> tree_name, name) == 0) found = 1; p = p -> next; } return (found); int main (void){ /* declaring variables to hold tree nodes */ tree tree1, tree2, tree3, tree4; char treename[20]; /* declaring the starting and traveling pointers */ tree *p, *start; /* putting tree names into each node */ strcpy (tree1.tree_name, "Maple"); strcpy (tree2.tree_name, "Fir"); strcpy (tree3.tree_name, "Pine"); strcpy (tree4.tree_name, "Oak");

/* setting the start of the list at tree1 */ start = &tree1; /* linking the other trees together */ tree1.next = &tree2; tree2.next = &tree3; tree3.next = &tree4; /* sets tree4 as the last node of the list */ tree4.next = NULL; /* checking if a tree is in the list */ printf ("Enter tree name to search: "); gets (treename); if (checktree(start, treename)) printf ("%s was found in our list of trees.\n", treename); else printf ("%s was not found in our list of trees.\n", treename); return (0); }

Filling a string (gets) A simpler gets function exists in C but its usage is considered dangerous. gets does not allow you limit the amount of input, which means it can potentially overflow the buffer into which the input is placed (for example you could read a sentence of 100 characters into an array size 10!). gets is deprecated (obsolete). Programs that use gets can actually be a security problem on your computer. Always use fgets.

Command-line arguments Advanced Topics Command-line arguments

int main (void)? All proper C main programs begin with int main (void).A main program is actually a function that takes arguments from the operating system and returns an integer (0). So far, we did not use any arguments in the main program because we did not send anything to the program from the operating system. That is why we used void as the sole argument for the main function. If we want to send information from the operating system to the program, we need to have command line arguments.

Command-line arguments The main program can have two command line arguments: 1. argc: an integer, representing the number of arguments (always at least 1). 2. argv: an array of strings containing the arguments themselves. All arguments coming from the operating system are strings. So instead of int main (void), the program header becomes int main (int argc, char * argv[ ])

Using command-line arguments #include<stdio.h> int main(int argc, char * argv[]){ int i; /*argument 0 identifies the program*/ printf("%s\n",argv[0]); /*the other arguments*/ for (i=1;i<argc;++i) printf("%s",argv[i]); return(0); }

The Command Line Now that we have seen how command-line arguments are processed by C programs let's see now how to send the command lines. Command lines are not written in C, they are direct text commands to the operating system. To access the OS commands in Windows XP or Vista, we use Start > Run > cmd

The Command Line Better still, we can use the command mode directly from Quincy. Tools > Options > Run > Prompt each time... Then, when we run the program, we will be prompted for the command line.

Numerical arguments / atoi() What if we needed to send numerical values into the command line? Since command line arguments are strings, we will need to convert those strings to numbers. For that we will need two new functions (need to include stdlib.h). The atoi() function converts a string into an integer, and returns that integer. The string must of course some sort of number, and atoi() will stop reading from the string as soon as a non numerical character has been read. atoi("45.78"); will return the integer 45.

atof() The function atof() converts a string into a double,then returns that value. The string must start with a valid number, but can be terminated with any non-numerical character, other than "E" or "e". atof( "42.57" ); will return the double 42.57. atof( "45.3e3" ); will return the double 45300.0.

Example!!!this is an extra practice for your knowledge only /* This program accepts two arguments in a specific order: 1) an integer number 2) a double number and sums them up */ #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { int a; double x, sum; if (argc ==3) printf("The arguments supplied are %s and %s.\n", argv[1], argv[2]); a = atoi (argv[1]); /* convert string to integer */ x = atof (argv[2]); /* convert string to double */ sum = a + x; printf ("The sum is: %f\n", sum); } else if (argc > 3) printf ("ERROR: Too many arguments supplied.\n"); printf ("ERROR: One argument expected.\n"); return (0);