Tuesday, February 6, 2007 Invest yourself in everything you do. There’s fun in being serious.” “Invest yourself in everything you do. There’s fun in being.

Slides:



Advertisements
Similar presentations
Lecture 3 Some commonly used C programming tricks. The system command Project No. 1: A warm-up project.
Advertisements

C Language.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
A file reminder Files are used to store data and information They are manipulated through a pointer to FILE (FILE *) This pointer is returned when opening.
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
Chapter 10.
File I/O. COMP104 Lecture 20 / Slide 2 Using Input/Output Files (Review) * A computer file n is stored secondary storage devices (hard drive, CD) n can.
Command-line arguments CS 201 Fundamental Structures of Computer Science.
Handout on Functions Passing Values to Functions #include int mult(int, int); int main() { int a = 10, b = 20; cout
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
Programming Review: Functions, pointers and strings.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
CS 192 Lecture 19 Winter 2003 February 9-10, 2004 Dr. Shafay Shamail.
Command line arguments. – main can take two arguments conventionally called argc and argv. – Information regarding command line arguments are passed to.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 15: Linked data structures.
String Constructors string str; // creates an empty //string string str(“abc”); // creates a string // from a C-string string str(aString); // creates.
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
DCT1063 Programming 2 CHAPTER 5 ADVANCED DATA TYPE (part 1) Mohd Nazri Bin Ibrahim Faculty of Computer Media and Technology TATi University College
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
1 CS 101 Lecture 2. 2 Input from the Keyboard Here is a program to accept input from the keyboard and put into into two variables. #include main(){ cout.
CS162 - Topic #11 Lecture: Recursion –Problem solving with recursion –Work through examples to get used to the recursive process Programming Project –Any.
ITEC 320 C++ Examples.
1 Operating Systems Lecture 2 UNIX and Shell Scripts.
File I/O ifstreams and ofstreams Sections 11.1 &
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
File IO and command line input CSE 2451 Rong Shi.
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
Sadegh Aliakbary Sharif University of Technology Spring 2011.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
 Building blocks of a C++ program  Each function has a name, which is used to call the function; functions call each other  You will write your own.
1 Command-Line Processing In many operating systems, command-line options are allowed to input parameters to the program SomeProgram Param1 Param2 Param3.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
COP 3275 – Character Strings Instructor: Diego Rivera-Gutierrez.
CS162 - Topic #7 Lecture: Dynamic Data Structures –Review of pointers and the new operator –Introduction to Linked Lists –Begin walking thru examples of.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Announcements Remember what we talked on Tuesday in terms of Makefiles and phony targets. Don’t lose points for this! BTW, the.PHONY target can appear.
 Data Streams  Numeric Output  Numeric Input  Multiple Numeric Output  Multiple Numeric Input  Character Output  Character Input  String Output.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Week 6 - Friday.  What did we talk about last time?  Pointers  Passing values by reference.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
5.13 Recursion Recursive functions Functions that call themselves
A bit of C programming Lecture 3 Uli Raich.
Command Line Arguments
Command line arguments
CSE 303 Concepts and Tools for Software Development
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Today’s Lecture I/O Streams Tools for File I/O
when need to keep permanently
File I/O.
Functions Reasons Concepts Passing arguments to a function
Linked Lists.
Presentation transcript:

Tuesday, February 6, 2007 Invest yourself in everything you do. There’s fun in being serious.” “Invest yourself in everything you do. There’s fun in being serious.” - Wynton Marsalis

Linked Lists struct node { int data; node* next; };

Linked Lists - easy example first... /*Build the list {1, 2, 3}*/ node* BuildOneTwoThree() { node* head = NULL; node* second = NULL; node* third = NULL; head = new node; second = new node; third = new node; head->data = 1; head->next = second; second->data = 2; second->next = third; third->data = 3; third->next = NULL; return head; }

Building the linked list... §BuildOneTwoThree() is fine as an example of pointer manipulation code, but it's not a general mechanism to build lists. §The best solution will be an independent function which adds a single new node to any list. § We can then call that function as many times as we want to build up any list.

Building the linked list... §The classic 3-Step Link In operation which adds a single node to the front of a linked list. The 3 steps are… 1) Allocate Allocate the new node in the heap and set its.data to whatever needs to be stored.

Building the linked list... §The classic 3-Step Link In operation which adds a single node to the front of a linked list. The 3 steps are… 1) Allocate Allocate the new node in the heap and set its.data to whatever needs to be stored. node* myNode; myNode = new node; myNode->data = data_user_wants_stored;

Building the linked list... 2) Link Next Set the.next pointer of the new node to point to the current first node of the list. (This is actually just a pointer assignment remember: "assigning one pointer to another makes them point to the same thing.”) 3) Link Head Change the head pointer to point to the new node, so it is now the first node in the list.

Building the linked list... 2) Link Next Set the.next pointer of the new node to point to the current first node of the list. (This is actually just a pointer assignment remember: "assigning one pointer to another makes them point to the same thing.”) myNode->next = head; 3) Link Head Change the head pointer to point to the new node, so it is now the first node in the list. head = myNode;

Building the linked list... §The problem is to write a general function which adds a single node to head end of any list.

Building the linked list... void WrongInsertAtFront(node* head, int data) { node* myNode = new node; myNode->data = data; myNode->next = head; head = myNode; } int main(void){ node* head = BuildOneTwoThree(); WrongInsertAtFront(head, 4); WrongInsertAtFront(head, 5); display(head); return 0; } BEWARE! This is WRONG way of inserting at front!

Building the linked list... void WrongInsertAtFront(node* head, int data) { node* myNode = new node; myNode->data = data; myNode->next = head; head = myNode; // NO this line does not work! } int main(void){ node* head = BuildOneTwoThree(); WrongInsertAtFront(head, 4); WrongInsertAtFront(head, 5); display(head); return 0; }

Different ways to InsertAtFront of a linked list node* ReturnsListAfterInsertAtFront(node* lsthead, int data){ node* myNode = new node; myNode->data = data; myNode->next = lsthead; lsthead = myNode; return lsthead; } int main(void){ node *head=NULL; head=ReturnsListAfterInsertAtFront(head, 14); head=ReturnsListAfterInsertAtFront(head, 15); head=ReturnsListAfterInsertAtFront(head, 11); display(head); return 0; }

Building the linked list... void CorrectInsertAtFront(node* &head, int data) { node* myNode = new node; myNode->data = data; myNode->next = head; head = myNode; } int main(void){ node *head=NULL; CorrectInsertAtFront(head, 4); CorrectInsertAtFront(head, 5); display(head); //OUTPUT? return 0; }

Building the linked list... void CorrectInsertAtFront(node* &head, int data) { node* myNode = new node; myNode->data = data; myNode->next = head; head = myNode; } int main(void){ node* head = BuildOneTwoThree(); CorrectInsertAtFront(head, 4); CorrectInsertAtFront(head, 5); display(head);//OUTPUT? return 0; }

Display the linked list... void display(node * mylist){ while (mylist!=NULL){ cout data<<endl; mylist=mylist->next; } int main(void){ node * list=BuildOneTwoThree(); display(list); return 0; }

Length of the linked list... int Length(node* head) { node* current = head; int count = 0; while (current != NULL) { count++; current = current->next; } return count; }

What is wrong here? struct node{ int data; node* next; }; void PrintList(node* list){ while(list!=NULL){ cout data<<endl; list++; }

What is wrong here? struct node{ int data; node* next; }; void PrintList(node* list){ while(list!=NULL){ cout data<<endl; list++; //Wrong! }

struct node{ int data; node* next; }; void PrintList(node* list){ while(list!=NULL){ cout data<<endl; list=list->next; }

SELF TEST: Building the linked list... void LinkTest() { node* head = BuildOneTwoThree(); node* myNode; myNode= new node; myNode->data = 4; myNode->next = head; head = myNode; // now head points to the list _________ ? display(head); }

§Append at end.

What Linked Lists Look Like? §More space per element stored §Operations towards the front of the list are fast while operations which access node farther down the list take longer the further they are from the front. § This "linear" cost to access a node is fundamentally more costly then the constant time [ ] access provided by arrays. § In this respect, linked lists are definitely less efficient than arrays.

Linked list operations Try on some examples!

ifstream fin; //declare input stream called fin for file ofstream fout ;//declare output stream called fout for file int num1, num2, sum; //connect fin to file called myinputfile.txt fin.open("myinputfile.txt"); //connect fout to file called myoutputfile.txt fout.open("myoutputfile.txt"); fin>>num1; //Read first number from myinputfile.txt fin>>num2; //Read second number from myinputfile.txt sum = num1+num2; //Write sum of numbers to myoutputfile.txt fout<<"sum of "<<num1<<" & "<<num2<<" is "<<sum<<endl; fout<<"Good bye!\n"; /*When we are done close files, i.e. disconnect the streams from files */ fin.close(); fout.close();

§Command line arguments to main can be used to pass information into a program when you run it. §C++ has two built-in, but optional, parameters to main( ) §int argc, char *argv[] receive the command line arguments §argc is an integer that holds the number of arguments on the command line. It will always be at least 1, because the name of the program qualifies as the first argument. §argv is a pointer to an array of character pointers §Each pointer in argv array points to a string containing a command line argument. argc and argv: Arguments to main( )

int main(int argc, char *argv[]) { if( argc!=4) { cout << "You forgot to give three inputs.\n"; return 1; } cout<<"My program file name is "<<argv[0]<<endl; cout<<"you typed "<<argv[1]<<" after it"<<endl; cout<<"this is the 2nd thing you typed: "<< argv[2] <<endl; cout<<"this is the 3rd thing you typed: "<<argv[3]<<endl; return 0; }

int main(int argc, char *argv[]) { int t, i; for(t=0; t<argc; ++t) { i = 0; while(argv[t][i]) { cout << argv[t][i]; ++i; } cout << endl; } return 0; } argc and argv: Arguments to main( )

int main(int argc, char *argv[]) { double a, b; if(argc!=3) { cout << "Usage: give two numeric-arguments\n"; return 1; } a = atof(argv[1]); b = atof(argv[2]); cout << a + b; return 0; } Passing Numeric Command Line Arguments

§double atof(const char*) converts the string form of a number into double (1.7E-308 to 1.7E+308) §int atoi(const char *) converts the string form of a number into integer (-32,768 to 32767) §long atol(const char *) converts the string form of a number into long integer (-2,147,483,648 to 2,147,483,647) char str[80]; gets(str); cout<<atoi(str); Passing Numeric Command Line Arguments