Академический Документы
Профессиональный Документы
Культура Документы
)
Problem 2
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include "list.h"
int main()
{
string s;
List l;
notEmpty = l.first(s);
while(notEmpty)
{
temp = s;
notEmpty = l.next(s);
if(s == temp && notEmpty) i++; //compare last string with the current string to count number of its
occurence
else {
//if the string is read for the first time, print the last string and its number of occurence and
reset the counter
system("PAUSE");
return EXIT_SUCCESS;
1
}
Problem 4
void List::reverse()
{
Link predN, currentN, nextN;
//at the begining, currentN is the head and its predessor is NUll as it will be the new tail
predN = NULL;
currentN = head;
//The reverse procedure is executed recursively till it reach tail where currentN = Null
while(currentN != NULL)
{
//preserve the next node before breaking the link between currentN and its next
nextN = currentN -> next;
//link between currentN and its predecessor predN
currentN->next = predN;
//move predN and currentN for the next iteration
predN = currentN;
currentN = nextN;
}
//after reversing the list, the new tail is the old head and vice versa
Link temp = head;
head = tail;
tail = temp;
Problem 5
void List::merge(List l)
{
//we want to merge 'list l' into 'this' list cosidering order of the nodes
bool notEmpty;
ListElemType e;
notEmpty = l.first(e);
while(notEmpty) //loop till the end of the list
{
insert(e); //insert e in this list
notEmpty = l.next(e); //get next item in the list
}
}
2
Problem 6
void List::sort()
{
Link N1, N2; //two pointers used to loop within the list
for(N1 = head; N1 != tail; N1 = N1->next) //first loop from head till the node before tail
for(N2 = N1->next; N2 != NULL; N2 = N2->next) //second loop from the next node of N1 till the
tail
if(N1->elem > N2->elem) //to sort the list ascending, compare then swap
{
ListElemType temp = N1->elem;
N1->elem = N2->elem;
N2->elem = temp;
}
}
Problem 7
In this solution, the remove is based on the position of the node in the list:
3
{
pred = pred->next;
k++;
}
deleted = pred->next;
if(deleted == NULL) //check if end of the list is reached, so position not found
return false;