Home › Forums › C Programming › Can You Help Me Plz! › Reply To: Can You Help Me Plz!
August 12, 2008 at 10:40 am
#3414
Humayan
Participant
Heres some code I found on my hard drive :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | #include<iostream.h><br /> //simple list<br /> struct node<br /> {<br /> int i;<br /> node * next;<br /> };<br /> void print ( node * );<br /> void addBack ( int , node *& , node *& );<br /> void addFront ( int , node *& , node *& );<br /> void destroy ( node *& );<br /> void main()<br /> {<br /> node * head = NULL;<br /> node * tail = NULL;<br /> char choice;<br /> int i;<br /> do<br /> {<br /> cout << "choose an operation: " << endl;<br /> cout << "1. add a node to back of list" << endl;<br /> cout << "2. add a node to front of list" << endl;<br /> cout << "3. print the list. " << endl;<br /> cout << "4. exit " << endl;<br /> cin >> choice;<br /> cin.get();<br /> cout << endl;<br /> switch ( choice )<br /> {<br /> case '1':<br /> {<br /> cout << " enter an integer : " ;<br /> cin >> i;<br /> addBack ( i , head , tail );<br /> };<br /> break;<br /> case '2':<br /> {<br /> cout << " enter an integer : " ;<br /> cin >> i;<br /> addFront ( i , head , tail );<br /> };<br /> break;<br /> case '3':<br /> {<br /> print ( head );<br /> };<br /> break;<br /> case '4':<br /> {<br /> cout <<"goodbye!" << endl;<br /> };<br /> break;<br /> default: cout << "bad choice !" << endl;<br /> <br /> };<br /> cout << endl;<br /> }<br /> while ( choice != '4' );<br /> destroy ( head ); <br /> <br /> <br /> }<br /> void print ( node * r )<br /> {<br /> node * t = r;<br /> cout << "This is the list: " << endl;<br /> <br /> while ( t != NULL )<br /> {<br /> cout << " " << t -> i << " ";<br /> t = t -> next;<br /> }<br /> cout << endl;<br /> }<br /> void addBack ( int n , node *& h , node *& t )<br /> {<br /> if ( h == NULL )<br /> {<br /> h = t = new node;<br /> t -> i = n;<br /> t -> next = NULL;<br /> }<br /> else<br /> {<br /> <br /> t -> next = new node;<br /> t -> next -> i = n;<br /> t -> next -> next = NULL;<br /> t = t -> next;<br /> <br /> }<br /> }<br /> void addFront ( int n , node *& h , node *& t )<br /> {<br /> if ( h == NULL ) //empty list<br /> {<br /> <br /> h = t = new node;<br /> t -> i = n;<br /> t -> next = NULL;<br /> }<br /> else //add to front<br /> {<br /> node * temp = h;<br /> <br /> h = new node;<br /> h -> i = n;<br /> h -> next = temp;<br /> }<br /> }<br /> void destroy ( node *& h )<br /> {<br /> node * temp;<br /> while ( h != NULL )<br /> {<br /> temp = h;<br /> h = h -> next;<br /> delete temp;<br /> }<br /> } |