If someone could help me find where i am going wrong, i have been working on this code for a long time but cannot get it right.
It takes a linked list to be sorted by passing *head as head pointer. The output of that function should be the same linked list sorted in ascending order such that the header node will be the smallest value in the
list.
void sortByCount (struct lnode** head) {
struct lnode* temp= (*head);
struct lnode* temp2 = (*head);
int i;
int j;
int counter = 0;
while(temp != NULL)
{
temp = nodeGetNext(temp);
counter++;
}
for( i = 1; i<counter; i++)
{
temp2=(*head);
bool flag = false;
for(j = 1; j<counter-i+1;j++)
{
if(countCmp(temp2,nodeGetNext(temp2))>0)
{
swap(head,temp2,nodeGetNext(temp2));
}
if(countCmp(temp2,nodeGetNext(temp2))== 0 && (wordCmp(temp2,nodeGetNext(temp2))>0))
{
swap(head,temp2,nodeGetNext(temp2));
flag = true;
//continue;
}
}
temp2 = nodeGetNext(temp2);
}
}
The problem is in this part of your loop:
if(countCmp(temp2,nodeGetNext(temp2))>0)
{
swap(head,temp2,nodeGetNext(temp2));
}
if(countCmp(temp2,nodeGetNext(temp2))== 0
&& (wordCmp(temp2,nodeGetNext(temp2))>0))
{
swap(head,temp2,nodeGetNext(temp2));
flag = true;
//continue;
}
If you decide to bubble up, and swap, then the second if check might choose to bubble up again (since the swap has happened, the next of temp2 will have changed). This is probably not what you intended. Instead, you probably meant to do the second if check only if the first if check failed. This is normally accomplished by adding an else to the if statement.
Related
I have this code and i want to print the tid of each node. I have segmatation fault in this for loop
printf("%d\n",tasks_head->head->tid); And i am not sure if the task_count[] works as i want. I want to save a counter++ in each position of the array.
struct Tasks
{
int tid;
int difficulty;
struct Tasks *next;
};
struct Head_GL
{
int tasks_count[3];
struct Tasks *head;
};
struct Head_GL *tasks_head=NULL;
int num=0;
int insert_task(int tid, int difficulty){
num++;
struct Tasks *prev=NULL;
struct Tasks *temp=NULL;
struct Tasks *new=(struct Tasks*)malloc(sizeof(struct Tasks));
tasks_head=(struct Head_GL*)malloc(sizeof(struct Head_GL));
tasks_head->head=(struct Tasks*)malloc(sizeof(struct Tasks));
tasks_head->tasks_count[0]=0;
tasks_head->tasks_count[1]=0;
tasks_head->tasks_count[2]=0;
tasks_head->head->difficulty=0;
tasks_head->head->tid=0;
tasks_head->head->next=NULL;
if(new==NULL)
return 0;
new->tid = tid;
new->difficulty = difficulty;
new->next = NULL;
if(difficulty==1)
tasks_head->tasks_count[0]++;
else if(difficulty==2)
tasks_head->tasks_count[1]++;
else
tasks_head->tasks_count[2]++;
if(tasks_head==NULL){
tasks_head->head = new;
return 1;
}
if( tasks_head->head->difficulty > difficulty){
new->next = tasks_head->head;
tasks_head->head= new;
return 1;
}
else{
prev = tasks_head->head;
temp = tasks_head->head->next;
while(temp != NULL && temp->difficulty < difficulty){
prev = temp;
temp = temp->next;
}
if(temp==NULL){
prev->next = new;
return 1;
}
else{
new->next = temp;
prev->next = new;
return 1;
}
}
}
int main(){
printf("hello1\n");
if(1==insert_task(1,1))
printf("alo");
if(1==insert_task(4,1))
printf("alo");
if(1==insert_task(3,2))
printf("alo\n");
printf("%d\n",num);
for(int i=0; i<num; i++){
printf("%d\n",tasks_head->head->tid);
tasks_head->head=tasks_head->head->next;
}
/*
for(int i=0; i<3; i++){
printf("%d",tasks_head->tasks_count[i]);
}*/
return 0;
}
There are a few problems with this code, but the most important is how you are affecting tasks_head.
At present you are malloc'ing a new tasks_head each time you enter insert_task, and recreating the head element, with these two lines:-
tasks_head=(struct Head_GL*)malloc(sizeof(struct Head_GL));
tasks_head->head=(struct Tasks*)malloc(sizeof(struct Tasks));
Normally you would either do this once, in a separate call to an initialisation function, or you can do it within insert_task by checking if it has already been performed.
You don't really need to create "head" separately, as the head will be the first "new" when you initialise the tasks_head global variable. So if you move this section of code down to below the creation of the "new" task, then you can assign it directly to the head.
If we look at the code where you are inserting the item into the linked list based upon its difficulty, then you can see that you are already doing this:-
if(tasks_head==NULL){
tasks_head->head = new;
return 1;
}
So the creation of a separate "head" is totally unnecessary.
The check here, by the way is exactly the check you would want to perform the once-off initialisation of "tasks_head", so if we take your code from above and move it into this section, then you will not keep reseting your global.
The downside of moving the initialisation, however, is that you've already tried to adjust the task difficulty count, so this also needs to come below, and we'll need to add an equivalent for the init case.
If you put all of those changes together you get the following:-
int insert_task(int tid, int difficulty){
num++;
struct Tasks *prev=NULL;
struct Tasks *temp=NULL;
struct Tasks *new=(struct Tasks*)malloc(sizeof(struct Tasks));
if(new==NULL)
return 0;
new->tid = tid;
new->difficulty = difficulty;
new->next = NULL;
if(tasks_head==NULL){
tasks_head=(struct Head_GL*)malloc(sizeof(struct Head_GL));
tasks_head->head=(struct Tasks*)malloc(sizeof(struct Tasks));
tasks_head->tasks_count[(difficulty != 1 && difficulty != 2)?2:difficulty-1]=1;
tasks_head->head = new;
return 1;
}
if(difficulty==1)
tasks_head->tasks_count[0]++;
else if(difficulty==2)
tasks_head->tasks_count[1]++;
else
tasks_head->tasks_count[2]++;
if( tasks_head->head->difficulty > difficulty){
new->next = tasks_head->head;
tasks_head->head = new;
return 1;
}
else{
prev = tasks_head->head;
temp = tasks_head->head->next;
while(temp != NULL && temp->difficulty < difficulty){
prev = temp;
temp = temp->next;
}
if(temp==NULL){
prev->next = new;
return 1;
}
else{
new->next = temp;
prev->next = new;
return 1;
}
}
}
The task_count difficulty mapping looks a little odd but I've tried to replicate your current behaviour, where a task of difficulty 1 is set to 0 and 2 is set to 1 and everything else is set to 2. I've done that with this slightly funky line using a tenery operator:
tasks_head->tasks_count[(difficulty != 1 && difficulty != 2)?2:difficulty-1]=1;
But it might just be that you want:
tasks_head->tasks_count[difficulty-1]=1;
if your task difficulty is only in the range 1-3.
Lastly we need to look at your loops in your main method which are currently modifying the global variable while trying to traverse the linked list.
for(int i=0; i<num; i++){
printf("%d\n",tasks_head->head->tid);
tasks_head->head=tasks_head->head->next;
}
I think you want to think about using a pointer to traverse this like the following:-
for(struct Tasks *p = tasks_head->head; p != NULL; p = p->next){
printf("%d\n", p->tid);
}
I'll leave you to think about the second loop to work out how you might wish to do something similar.
I am trying to create a linked list and sort it by Bubble Sort. I succeeded to create the linked list, but when I am trying to Bubble Sort it, some accidents occur and I do not know the problem. What is the problem?
#include <stdio.h>
#include <stdlib.h>
//the struct of LinkedList
typedef struct Node
{
int data;
struct Node * pNext;
}NODE,*PNODE;
PNODE createList();//Creat one LinkedList
int lengthList(PNODE pHead);//get the length of LinkedList
void sortList(PNODE);//bubble sort
int main()
{
int length;
PNODE pHead=NULL;
pHead=createList();
sortList(pHead);
return 0;
}
//Create LinkedList
PNODE createList()
{
int i,n;
int val;
PNODE pHead=(PNODE)malloc(sizeof(NODE));
if(pHead==NULL)
{
printf("failed to create!\n");
exit(-1);
}
pHead->pNext=NULL;
PNODE pTail=pHead;
printf("please input the length of the LinkedList:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("number %d is:\n",i+1);
scanf("%d",&val);
PNODE pNew=(PNODE)malloc(sizeof(NODE));
if(pNew==NULL)
{
printf("failed to create\n");
exit(-1);
}
pNew->data=val;
pTail->pNext=pNew;
pNew->pNext=NULL;
pTail=pNew;
}
return pHead;
}
//get the length of LinkedList
int lengthList(PNODE pHead)
{
int i=0;
PNODE p=pHead->pNext;
while(p!=NULL)
{
i++;
p=p->pNext;
}
return i;
}
//bubble sort
void sortList(PNODE pHead)
{
int i,j,t,len;
PNODE p,q;
len=lengthList(pHead);
p=pHead->pNext;
for(i=0;i<len-1;i++)
{
for(j=0;j<len-i;j++)
{
q=p->pNext;
if( p->data > q->data)
{
t=p->data;
p->data=q->data;
q->data=t;
}
p=q;//here may be the error
}
}
return;
}
You are running off the end of your list in sortList
p=pHead->pNext;
for(i=0;i<len-1;i++)
{
for(j=0;j<len-i;j++)
{
q=p->pNext;
....
p=q;//here may be the error
}
}
Bug 1) Your list is only len long but you are attempting to advance p to p->pNext far more then len times.
Bug 2) pHead does not need to be a full NODE - it's just a PNODE pointer. You never use its data field. You should have pHead point to the first node in the list, and then start your iteration at pHead rather than pHead->pNext.
Bug 3) You never clean up your memory allocations.
As #Airsource pointed out the bugs, keep in mind most of them are caused because of poor designing choice of your program. Try to do it like below & you will run into less errors
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct _Node{
int data;
struct _Node* next;
}Node;
typedef struct {
Node* headPtr;
Node* tailPtr;
unsigned size;
}List;
static void create_node(List* list, int element) {
if (list->headPtr == NULL) {
// List is empty
list->headPtr = (Node* )malloc(sizeof(Node));
list->headPtr->data = element;
list->headPtr->next = 0;
list->tailPtr = list->headPtr;
list->size++;
}else{
// List was already populated
Node* temp = (Node* )malloc(sizeof(Node));
temp->data = element;
temp->next = 0;
list->tailPtr->next = temp;
list->tailPtr = temp;
list->size++;
}
}
void create_list(List* list, int length){
int ele;
int i;
list->headPtr = list->tailPtr = 0;
list->size = 0;
for (i = 0; i < length; i++) {
scanf("%d", &ele);
create_node(list, ele);
}
}
void print_list(List* list){
Node* loop = list->headPtr;
while(loop){
printf("%d ", loop->data);
loop = loop->next;
}
printf("\n");
}
int main(){
List* list;
int n;
printf("Enter the length of the list: ");
scanf("%d", &n);
create_list(list, n);
print_list(list);
bubble_sort(list);
print_list(list);
if (cleanup(list))
printf("Memory rescued!!\n");
else
printf("OOPS!! Error\n");
return 0;
}
Moreover, you can get the size anytime just by list->size. No need for separate function to do that.
Finally to sort it using bubble sort you could do something like this below
void bubble_sort(List* list) {
int i, j;
Node* first, *second;
int temp;
first = list->headPtr;
second = list->headPtr->next;
for (i = 0; i < list->size - 1; i++) {
for (j = 0; j < list->size - i - 1; j++) {
if (first->data > second->data){
temp = first->data;
first->data = second->data;
second->data = temp;
}
first = second;
second = second->next;
}
first = list->headPtr;
second = list->headPtr->next;
}
}
and for cleanup you do this
bool cleanup(List* list) {
Node* curr = list->headPtr;
Node* nxt = list->headPtr->next;
while(nxt){
free(curr);
curr = nxt;
nxt = curr->next;
}
list->headPtr = list->tailPtr = 0;
list->size = 0;
return !nxt ? true: false;
}
There are couple of bugs in your program. I will address them one by one:
Line 28 PNODE pHead=(PNODE)malloc(sizeof(NODE));
Here you are allocating a memory and creating a node before checking if n>0 or not.
Line 36 printf("please input the length of the LinkedList:");
Now up to this point you have created a one node, head node which has no value in it (so contains garbage)
In effect your createList() creates a linked list with n+1 nodes instead of n and the head->value contains garbage.
Solution:
printf("please input the length of the LinkedList:");
scanf("%d", &n);
for(i=0; i<n; i++)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(pNew == NULL)
{
printf("failed to create!\n");
exit(-1);
}
scanf("%d", &val);
pNew->data = val;
pNew->pNext = NULL;
if (!i)
pHead = pNew;
else
pTail->pNext = pNew;
pTail = pNew;
}
return pHead;
Line 59 PNODE p=pHead->pNext;
Here you are counting nodes starting from the second node (leaving out head). No wonder you will get length as n as you have created a linked list of length n+1 in your createList()
Imagine what if n = 0 and thus pHead = NULL?
Then this line will result in SegFault.
Solution:
change PNODE p=pHead->pNext; to PNODE p = pHead;
Line 73 p=pHead->pNext;
Here you will start sorting excluding the first node, head node.
Also this should be inside the outter for and outside of the inner for to reset the p to first node for each pass.
Line 76 for(j=0;j<len-i;j++)
Here j must be less than len - 1 - i as in pass 1 (i = 0) in the worst case j will be equal to len-1 for j < len-i, where p will point to the last node of linked list and q will be NULL as q = p -> pNext. Which will make q->data to result in SegFault.
To summarise, your sort routine is producing SegFault in the very first Pass and even if it didn't (by properly adjusting the loop-terminating expression in inner for) the outer for loop is contributing nothing towards the sorting except increasing the time complexity.
Solution:
for(i = 0; i < len - 1; i++)
{
p = pHead;
for(j = 0; j < len - 1 - i; j++)
{
q = p -> pNext;
if(p->data > q->data)
{
t = p -> data;
p -> data = q -> data;
q -> data = t;
}
p = q;
}
}
A question:
How are you checking whether element have been sorted or not?
A printList() routine would have been helpful in spotting the above bugs.
"Always verify whether you correctly stored the input or not by explicitly printing the same before processing it!"
trying to get a function to run that will bubble sort a link list from smallest to largest number. I don't want the data to be moved around in the link list instead have the pointers be pointing elsewhere in case each link needs to hold a lot of data.
In each link I have a INT arrivalTime field that will house a integer value. THis number determines where the link should be in the list.
My program seems to hang at the moment, I'd appreciate if anyone could fix it up, Thanks
bubble sort function
void bubbleSort(struct order *start)
{
int swapped, i;
processData *current = start;
processData *temp;
struct order *lptr = NULL;
/* Checking for empty list */
if (current == NULL)
printf("null \n");
do
{
swapped = 0;
current = start;
while (current->next != lptr)
{
if (current->arrivalTime > current->next->arrivalTime)
{
temp = current;
current = current->next;
current->next = temp;
swapped = 1;
}
current = current->next;
}
lptr = current;
}
while (swapped);
}
structure of link list
struct order
{
int name;
int arrivalTime;
int quanta;
struct order * next;
};
typedef struct order processData;
Swapping two adjacent items in a singly-linked-list requires that you change three next pointers.
If the order is A --> B --> C --> D and you swap B with C to get A --> C --> B --> D then
A->next needs to point to C instead of B
B->next needs to point to D instead of C
C->next needs to point to B instead of D
This is a very slow thing you're trying to do - see this paper on comparing ways to sort a linked list.
Currently, your algorithm will never terminate because in your while loop, you set lptr = current, but then test whether current->next == lptr. This will never return true unless one of your list members points to itself.
If you do have a definite use case to bubble sort the linked list, consider this: The purpose of a linked list is that you access it by working sequentially from the list head to the item you want. If your initial list head is not the smallest or the largest and you're only changing pointers, you need to keep track of where the head of the list is.
I did think of a way to do it loosely based on yours, see below. Sorry it's a bit messy - I'm not a C expert (hope the memory allocation is OK...) and I'm sure there are optimisations. In particular I'm sure there are better ways to pass the headOfList pointer back to the main algorithm. I've tested it for a number of 100 member lists of structs with some negative numbers. I've left the code to generate them with random arrival times in main() so you can just paste this in where your old code was and run it.
processData *bubbleSort(processData *start)
{
int swapped;
processData *current = start;
processData *lheadptr = start;
processData *previous = NULL;
processData *oldPrevButBigger;
processData *oldAfterThisPair;
/* Checking for empty list */
if (current == NULL)
{
printf("null \n");
return NULL;
}
do
{
swapped = 0;
current = lheadptr;
previous = NULL;
while (current->next) //Stop when current->next is null (i.e. end of list)
{
if (current->arrivalTime > current->next->arrivalTime)
{
oldPrevButBigger = current;
oldAfterThisPair = current->next->next;
current = current->next;
current->next = oldPrevButBigger;
current->next->next = oldAfterThisPair;
if (!previous)
{
//If no previous, this was the head of the list, so need to update
lheadptr = current;
}
else
{
// If there is a "previous", then we're not at head of list, so need
// to update that pointer too
previous->next = current;
}
swapped = 1;
}
previous = current;
current = current->next;
}
}
while (swapped);
return lheadptr;
}
int main()
{
srand(time(NULL));
int NUM = 100;
processData* pointToLast = NULL;
int i;
processData orders[NUM];
//Generate a list with random arrival times (last member of the list generated first
for (i = 0; i < NUM; i++ )
{
orders[i].name = i;
orders[i].arrivalTime = rand()-1000000000;
orders[i].quanta = 500;
orders[i].next = pointToLast;
pointToLast = &orders[i];
}
printf("List before\n");
printf("===========\n");
for (i=0; i < NUM; i++)
{
printf("%i;%i;%i\n", pointToLast->name, pointToLast->arrivalTime, pointToLast->quanta);
pointToLast = pointToLast->next;
}
processData* newListHead = bubbleSort(&orders[NUM-1]);
printf("List after\n");
printf("===========\n");
for (i=0; i < NUM; i++)
{
printf("%i;%i;%i\n", newListHead->name, newListHead->arrivalTime, newListHead->quanta);
newListHead = newListHead->next;
}
return 0;
}
I'm writing a programme that needs to transverse threw 64 linked lists. (each node having one integer variable named val) it needs to compare each node and if the val is equal to another val in any other node of any list it must record it.
i've written a function that transverse threw the lists but after it prints the results that they equal it crashes, my function looks like this (n = 64):
void scanlist(int n)
{
int i = 0;
int j = 0;
for(i=0; i < n; i++)
{
struct node *temp; //Declare temp
temp = heads[i]; //Assign Starting Address to temp
int x = i++;
struct node *temp2; //Declare temp2
temp2 = heads[x]; //Assign Starting Address to temp2
while(temp != NULL)
{
if(temp->val == temp2->val)
{
printf("theyre on the same line, %d = %d \n", temp->val, temp2->val);
temp2 = temp2->next;
continue;
}
else if(temp->val != temp2->val)
{
temp2 = temp2->next;
continue;
}
else if(temp2 == NULL)
{
temp = temp->next;
temp2 = heads[x];
continue;
}
}
}
}
my linked list code looks like this:
struct node
{
int val;
struct node *next;
} ;
struct node* heads[64]; // array with the roots of the lists
struct node* currs[64]; // array holding pointers to current positions in list
struct node* create_list(int val, int listNo){
struct node *ptr = (struct node*)malloc(sizeof(struct node));
ptr->val = val;
ptr->next = NULL;
heads[listNo] = currs[listNo] = ptr;
return ptr;
}
void setup_list_array(int n){
int i;
for(i=0; i<n; i++)
{
heads[i] = NULL;
currs[i] = heads[i];
}
}
thanks for any help in advance, hope i was clear.
First, a few small comments on the 'Question' code:
void scanlist(int n)
{
int i = 0;
int j = 0;
It appears that 'j' is unused.
for(i=0; i < n; i++)
Perhaps it would be more efficent to this to
for(i=0; i < (n-1); i++)
This will avoid referencing the last 'heads[]', due to it being already compared.
{
struct node *temp; //Declare temp
temp = heads[i]; //Assign Starting Address to temp
int x = i++;
Perhaps 'i' is incremented in order to initialize 'x' to 'i + 1'; however, this statement is equivelant to 'x=i; i=i+1;', which does not appear to me helpful.
struct node *temp2; //Declare temp2
temp2 = heads[x]; //Assign Starting Address to temp2
Due to the previously stated mis-initialization of 'x', 'temp' and 'temp2' now point to the same 'head[]' element.
while(temp != NULL)
{
if(temp->val == temp2->val)
{
printf("theyre on the same line, %d = %d \n", temp->val, temp2->val);
temp2 = temp2->next;
continue;
}
else if(temp->val != temp2->val)
The 'else' statement can be omitted here. if '(temp->val == temp2->val)' [above] evaluates to 'TRUE', the 'continue' statement will cause program flow back to the top of the loop.
In addition, the statement 'if(temp->val != temp2->val)' can be omitted due to it will always evaluate to 'TRUE'
{
temp2 = temp2->next;
continue;
}
else if(temp2 == NULL)
Due to this 'else' statement, if either of the above 'if' statements evaluate to 'TRUE', this code will not be executed. This appears to be a flaw.
{
temp = temp->next;
temp2 = heads[x];
continue;
}
}
}
}
Below, another way to implement this method (included comments describe what is going on).
void scanlist(
int n
)
{
int i;
/* Iterate the list heads. */
for(i=0; i < (n-1); ++i)
{
struct node *temp = heads[i]; // Declare temp and assign Starting Address
/* Iterate primary list nodes. */
while(temp)
{
int j;
/* Iterate list heads to compare */
for(j=i+1; j < n; ++j)
{
struct node *temp2 = heads[j]; //Declare temp2 and assign Starting Address
/* Iterate list nodes to compare */
while(temp2)
{
if(temp->val == temp2->val)
printf("theyre on the same line, %d = %d \n", temp->val, temp2->val);
temp2=temp2->next;
}
}
}
temp=temp->next;
}
return;
}
I have a Segmentation error, maybe a lot more after I run it, but I can't check anything else now because of that.
The program should work like this:
When user types in 5 numbers, they should print out in ascending order
If the user enter the number already exit, then remove the original value
If the user enter a native value, print List Backwards
This is my code so far:
#include <stdio.h>
#include <stdlib.h>
struct element {
int i;
struct element *next;
};
void insert (struct element **head, struct element *new)
{
struct element *temp;
temp = *head;
while(temp->next != NULL)
{
if((*head==NULL))
{
head = malloc(sizeof(struct element));
//temp->i = i;
temp->next = new;
new = temp;
}
else if(temp->i == new->i)
{
new = malloc(sizeof(struct element));
free(new);
//purge(&head,&new);
}
else if(temp->i < new->i)
{
temp->i = new->i;
}
else if(temp->i > new->i)
{
new = new->next;
}
}
}
void purge (struct element *current, struct element *predecessor)
{
predecessor->next = current -> next;
free(current);
}
void printList (struct element *head)
{
while(head)
{
printf("%d", head -> i);
head = head->next;
}
}
void printListBackwards (struct element *ptr)
{
if(ptr == NULL)
{
printf("list is empty \n");
return;
}
if(ptr->next != NULL)
{
printListBackwards(ptr->next);
}
printf("print %p %p %d\n", ptr, ptr->next, ptr->i);
}
int main()
{
int n = 0;
int count = 5;
printf("enter a Number: \n");
scanf("%d",&n);
struct element *new;
new = malloc(sizeof(struct element));
struct element *head = NULL;
new->i = n;
while(count!=0)
{
insert(&head,new);
printList(head);
count++;
}
}
In the main() function, you only allocate and create one element with malloc(); you then try to add it to your list 5 times. This is going to cause confusion. You should allocate a node once for each element you add to the list.
struct element *head = NULL;
while (count!=0)
{
printf("enter a Number: \n");
if (scanf("%d", &n) != 1)
break;
struct element *new = malloc(sizeof(struct element));
if (new == 0)
break;
new->i = n;
new->next = NULL;
insert(&head, new);
printList(head);
count--;
}
Note that the revised code checks the result of both scanf() and malloc(). It also sets the new element's next pointer to NULL. And it counts down rather than up; this is likely to use less memory.
I've not tested this so there could be (and very probably are) other problems, but this is likely to work better (fix some of the problems, but not all of the problems).
You do need to learn how to use a debugger, at least enough to get the stack trace so you know which line of code is causing the crash.
Do you really need a linked list? It seems the problem statement says that user can enter only 5 numbers... if so, why not just use an array of 5 elements? Following are some ideas.
enum { N = 5 };
typedef struct Element {
int number;
bool present;
} Element;
Element elements[ N ];
Init:
for( i = 0; i != N; ++i ) {
elements[i].number = 0;
elements[i].present = false;
}
Insert "inputNumber":
for( i = 0; i != N; ++i ) {
if( elements[i].present == false ) {
elements[i].number = inputNumber;
elements[i].present = true;
}
}
Remove "removeNumber":
for( i = 0; i != N; ++i ) {
if( elements[i].number == removeNumber ) {
elements[i].present = false;
}
}
Print Backwards:
for( i = N; i != 0; --i ) {
printf( "%d\n", elements[i].number );
}
In main, you should set new->next = NULL; [or somewhere in the beginning of insert]
This bit of code is just messed up:
head = malloc(sizeof(struct element));
//temp->i = i;
temp->next = new;
new = temp;
You should, probably, set
*head = new;
But you also need to set *head->next = NULL;
This bit is complete nonsense:
new = malloc(sizeof(struct element));
free(new);
//purge(&head,&new);
You would want to free new.
else if(temp->i < new->i)
{
temp->i = new->i;
}
else if(temp->i > new->i)
{
new = new->next;
}
This is also quite wrong. I think the last one should do
temp = temp->next;
Do yourself a favour, draw up on a piece of paper, boxes
HEAD
!
v
+-----+
! i=3 !
+-----+ +-----+
!------->! i=4 !
+-----+
!-------->NULL
And then walk through it and see how your code inserts, removes, etc.
[Can I also suggest that you don't use C++ reserved words in your code - new is a C++ reserved word. It means that your code CERTAINLY won't compile in a C++ compiler, which is a bad thing to prevent. Sure, there are several other things that may need changing, but a simple thing like "not calling a variable new" shouldn't be one of the things it fails on].