Ascending order Linked List in C - c

I have been tasked with implementing an insert function which will be used in a project. If user input is 1 2 3 4, the desired output of the print statement would be 1, 2, 3, 4. Currently, my print statement is returning 4, 3, 2, 1 but I believe this to be correct. I think my issues lie within my input function (which is nested within a while loop to get user input). This is using C
Any help would be appreciated.
struct set {
int data;
struct set* next_p;
};
struct set* getInput( struct set* head_p, int val ) {
struct set* temp;
temp->data = val;
temp->next_p = head_p;
return temp;
} /* getInput */
struct set* makeSet( struct set* head_p ) {
int val;
printf( "Please enter a positive integer, or a negative to stop: \n" );
scanf("%d", &val);
while ( 100 ) {
head_p = getInput( head_p, val );
scanf("%d", &val);
}
return head_p;
}

Sorry mate was busy but hey i fixed your code.I already mentioned the problem was that you were appending the newNode before the head.
#include <stdio.h>
#include <stdlib.h>
struct set {
int data;
struct set* next_p;
};
struct set* getInput( struct set* ptr, int val )//appends a newNode to ptr which is the last node of Linked list
{
struct set* temp=NULL;
temp = (struct set*)malloc(sizeof(struct set));
temp->data = val;
temp->next_p = NULL;
if(ptr!=NULL)//if Linked list has been created,i.e.,only if we have a head run this
ptr->next_p=temp;
return temp;
} /* getInput */
struct set* makeSet( struct set* head_p ) {
int val;
struct set* ptr=head_p;
printf( "Please enter a positive integer, or a negative to stop: \n" );
while (1) {
scanf("%d", &val);
if(val>=0)
ptr=getInput( ptr, val );//appends only value>=0 to linked list else breaks from the infinite loop
else
break;
if(head_p==NULL)//To set the head of the linked List! True only for the 1st node in the linked list
head_p=ptr;
}
return head_p;
}
void display(struct set* head_p)
{
if(head_p==NULL)
printf("\nno List in Memory\n"); //
else
{
struct set* ptr=head_p;
printf("\n the linked list is\nHead");
while(ptr!=NULL)
{
printf("-->%d",ptr->data);
ptr=ptr->next_p;
}
}
}
int main()
{
struct set* head_p=NULL;
head_p=makeSet((head_p));//returns the head of the linked list created
display(head_p);//displays the linked list
return 0;
}

struct set* make_aSet(int val ) {
struct set* temp;
if((temp = malloc(sizeof(*temp))) != NULL){
temp->data = val;
temp->next_p = NULL;
} else {
fprintf(stderr, "can't make new a set\n");
}
return temp;
}
struct set* makeSet(void) {
struct set dummy_head, *current = &dummy_head;
int val;
printf( "Please enter a positive integer, or a negative to stop: \n" );
while (1==scanf("%d", &val) && val >= 0 ) {
current->next_p = make_aSet( val );
current = current->next_p;
}
return dummy_head.next_p;
}

Related

Deleting first node in linked list

I am having problems with my homework, which deals with editing linked list. My code seems to work fine, except it does not delete data items with student ID=1 (or the first node in linked list).
When I try to delete the first node on the linked list (or, delete(1) within main()), it returns "Student not found" message.
Could someone please tell me what went wrong? Thanks.
/****************************************************************************
Date : 12 August 2015
Assignment : Use linked list to build a database of student records, which supports find(), insert() and delete()
****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
/* Define structure studentNode that contains ID, name, GPA and pointer to next studentNode*/
typedef struct student {
int ID;
char *name;
float GPA;
struct student *nextStudentNode;
} studentNode;
/* Initialize header */
studentNode *header;
/* Function prototypes*/
void insert(int ID, char *name, float GPA);
void printList();
void delete(int ID);
/* Main function which runs through while loop until sentinel value of q is typed by user. */
int main() {
insert(3, "John", 3.5);
insert(12, "Smith", 2.8);
insert(1, "Mary", 1.8);
printList();
delete(1); /***** there seems to be a problem here*********/
delete(12);
delete(3);
printList();
return 0;
}
/* Insert new student data */
void insert(int ID, char *name, float GPA) {
studentNode *newStudent = (studentNode*)malloc(sizeof(struct student));
newStudent->ID = ID;
newStudent->name = name;
newStudent->GPA = GPA;
newStudent->nextStudentNode = header;
header = newStudent;
}
/* Run through linked list one by one to print all data items */
void printList() {
studentNode *tempNode;
for (tempNode = header ; tempNode != NULL ; tempNode = tempNode->nextStudentNode) {
printf( "ID:%d name:%s GPA:%f\n" , tempNode->ID, tempNode->name, tempNode->GPA);
}
}
/* Delete student data */
void delete(int inputID) {
studentNode *tempNode;
studentNode **headerPtr = &header;
for (tempNode = *headerPtr ;
tempNode->nextStudentNode->ID != inputID && tempNode->nextStudentNode->nextStudentNode != NULL;
tempNode = tempNode->nextStudentNode);
studentNode *nodeToDelete = tempNode->nextStudentNode;
if (nodeToDelete->ID != inputID) {
printf("Student not found.\n");
} else {
printf("ID:%d name:%s GPA:%f is deleted.\n" , nodeToDelete->ID, nodeToDelete->name,
nodeToDelete->GPA);
tempNode->nextStudentNode = nodeToDelete->nextStudentNode;
free(nodeToDelete);
}
}
The problem is in this for:
for( tempNode = *headerPtr ; tempNode->nextStudentNode->ID != inputID && tempNode->nextStudentNode->nextStudentNode != NULL ; tempNode = tempNode->nextStudentNode );
You are starting checking from second student, not for the first one. So you are going to the end of the list without finding a proper ID.
UPDATE: I mean the list order.
This condition in the first loop of the function
tempNode->nextStudentNode->ID != inputID && tempNode->nextStudentNode->nextStudentNode != NULL ;
is wrong because it skips ID in the first node.
The function can be written simpler
/* Delete student data */
void delete( int inputID )
{
studentNode *prev = NULL;
studentNode *tempNode = head;
while ( tempNode && tempNode->ID != inputID )
{
prev = tempNode;
tempNode = tempNpde->nextStudentNode;
}
if ( tempNode )
{
if ( !prev ) head = tempNode->nextStudentNode;
else prev->nextStudentNode = tempNode->nextStudentNode;
free( tempNode );
}
}

Sorting the numbers in a list / C

I need to sort the numbers that are entered in a list, but I am doing something wrong and it's sorting all of them except the first one.Any ideas how to fix this?
Here's my code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* List;
void Add (struct node* p, int d)
{
struct node* q;
q=malloc(sizeof(struct node));
if (q==NULL)
printf("Not enaugh memory!");
else
{
q->data=d;
if(List==NULL)
{
q->next=NULL;
List=q;
}
else
{
struct node *ptr=List;
while((ptr->next!=NULL)&&(ptr->next->data>d))
{
ptr=ptr->next;
}
q->next=ptr->next;
ptr->next=q;
}
}
}
int main()
{
int n,i,a;
printf("How much numbers are you going to enter? ");
scanf("%d",&n);
for (i=1; i<=n; i++)
{
printf("\nEnter a number: ");
scanf("%d",&a);
Add(List,a);
}
printf("\nThe sorted numbers are: ");
struct node *ptr=List;
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->next;
}
printf("\n\n");
system("PAUSE");
return 0;
}
Thanks for the help in advance :-)
in add() function,
if(List==p)
this statement is true for all elements you insert to list since the call to add is,
Add(List,a);
so p=List. therefore the sorting code written in else part is not executed.
Also add statements to check for empty initial list.
You can use code similar to this,
void Add (int d)
{
struct node* q;
q=malloc(sizeof(struct node));
if (q==NULL)
printf("Not enaugh memory!");
else
{
q->data=d;
if(List==NULL)
{
q->next=NULL;
List=q;
}
else
{
struct node *ptr=List;
while((ptr->next!=NULL)&&(ptr->next->data>d))
{
ptr=ptr->next;
}
q->next=ptr->next;
ptr->next=q;
}
}
}
Since list is a global variable you dont need to pass it to Add() function. change the function call to
Add(a);
void Add (struct node* p, int d){
struct node* q;
q=malloc(sizeof(struct node));
if (q==NULL)
printf("Not enaugh memory!");
else{
q->data=d;
if(List==NULL || List->data < d){//modify this line
q->next= List;//and change NULL to List
List=q;
} else {
struct node *ptr=List;
while((ptr->next!=NULL)&&(ptr->next->data>d)){
ptr=ptr->next;
}
q->next=ptr->next;
ptr->next=q;
}
}
}
You always call Add with List as the first parameter, so it's alway true inside Add that (List==p). Consequently each new item is just inserted at the front of the list and there is no sorting at all.
EDIT 1
A good practice would be sending a list to the Add routine as a parameter. Or, if you want to keep it external, just don't give it to Add at all and test if(List == NULL)
void Add( int d)
{
// ... alloc 'q' and fill q->d here, then:
if(List == NULL)
{
q->next = NULL;
List = q;
}
else
{
struct node *b; // put q after b
for( b = List; b->next != NULL; b = b->next)
if( b->next->data >= d)
break;
q->next = b->next;
b->next = q;
}
}
EDIT 2
Example of transferring the list to a function by parameter
void Add( struct node **n, int d)
{
// ... alloc 'q' and fill q->d here, then:
while( *n != NULL && (*n)->data < d)
n = & (*n)->next;
q->next = *n;
*n = q;
}
int main()
{
// ...
Add( &List, a);
// ...
}

Write a function that rearranges a linked list to put the nodes in even positions after the nodes in odd positions in the list

Write a function that rearranges a linked list to put the nodes in even positions after the nodes in odd positions in the list, preserving the relative order of both the evens and the odds.
I found this problem in the book Algorithm in c writtern by Sedgewick. I have tried but failed. I trid to put all nodes in even positions on another linked list. It's grateful for you to help me. A good idea is enough. Thanks :).
This is my Code in C.
/*
* File: rearranges.c <Exercise 3.36>
* Note: Write a function that rearranges a linked list to put the nodes in even
* positions after the nodes in odd positions in the list, preserving the
* relative order of both the evens and the odds.
* NOTICE: I think it's necessary to use linked list with a dummy head.
* Time: 2013-10-26 10:58
*/
#include <stdio.h>
#include <stdlib.h>
#define LEN 11
typedef struct node *link;
struct node {
int item;
link next;
};
/* Traverse a linked list with a dummy head. */
void traverse(link t) {
link x = t->next;
while (x != NULL) {
printf("%d ", x->item);
x = x->next;
}
putchar('\n');
}
/* Detach even positon nodes from a linked list. */
link detach(link t) {
link u = malloc(sizeof(*u));
link x = t, y = u;
/* x is odd position node. We should ensure that there's still one even
* position node after x. */
while (x != NULL && x->next != NULL) {
y->next = x->next;
x->next = x->next->next;
x = x->next;
y = y->next;
y->next = NULL;
}
return u;
}
/* Combine two linked list */
link combine(link u, link t) {
link x = u;
link y = t->next;
while (y != NULL) {
link n = y->next;
y->next = x->next;
x->next = y;
x = x->next->next;
y = n;
}
return u;
}
/* The function exchanges the position of the nodes in the list. */
link rearranges(link t) {
link u = detach(t);
link v = combine(u, t);
return v;
}
int main(int argc, char *argv[]) {
int i;
link t = malloc(sizeof(*t));
link x = t;
for (i = 0; i < LEN; i++) {
x->next = malloc(sizeof(*x));
x = x->next;
x->item = i;
x->next = NULL;
}
traverse(t);
traverse(rearranges(t));
return 0;
}
curr=head;
end=lastOfList;//last node if size of list is odd or last-1 node
for(int i=1;i<=listSize()/2;i++)
{
end->next=curr->next;
end=end->next;
end->next=null;
if(curr->next!=null)
if((curr->next)->next!=null)
curr->next=(curr->next)->next;
curr=curr->next;
}
You can implement a recursive solution where each call returns an updated node that will serve as the new next reference for the upper caller. We just have to go down the list until we find the last element, and then move every even node to the end of the list, and update the reference to the last element. Here's my solution (please try to do it yourself before looking at my and other solutions):
struct node {
int val;
struct node *next;
};
struct node *reorder_aux(struct node *l, int count, struct node **last);
struct node *reorder(struct node *l) {
struct node *x;
if (l == NULL)
return NULL;
return reorder_aux(l, 1, &x);
}
struct node *reorder_aux(struct node *l, int count, struct node **last) {
struct node *n;
if (l->next == NULL) {
*last = l;
return l;
}
n = reorder_aux(l->next, count+1, last);
if (count & 1) {
l->next = n;
return l;
}
else {
(*last)->next = l;
l->next = NULL;
*last = l;
return n;
}
}
At each step, if the current node l is an even node (as determined by count), then we append this node to the end, and tell the upper caller that its next pointer shall be updated to our next (because our next will be an odd node). In case we're an odd node, we just have to update our next pointer to whatever the recursive call returned (which will be a pointer to an odd node), and return the current node, since we will not move ourselves to the end of the list.
It's a nice exercise!
#include <stdio.h>
struct list {
struct list *next;
int ch;
};
void swap_odd_even (struct list **pp)
{
struct list *one, *two ;
for( ; (one = *pp) ; pp = &one->next) {
two = one->next;
if (!two) break;
*pp = two;
one->next = two->next;
two->next = one;
}
}
struct list arr[] =
{ {arr+1, 'A'} , {arr+2, 'B'} , {arr+3, 'C'} , {arr+4, 'D'}
, {arr+5, 'E'} , {arr+6, 'F'} , {arr+7, 'G'} , {arr+8, 'H'}
, {arr+9, 'I'} , {arr+10, 'J'} , {arr+11, 'K'} , {arr+12, 'L'}
, {arr+13, 'M'} , {arr+14, 'N'}, {arr+15, 'O'} , {arr+16, 'P'}
, {arr+17, 'Q'} , {arr+18, 'R'} , {arr+19, 'S'} , {arr+20, 'T'}
, {arr+21, 'U'} , {arr+22, 'V'}, {arr+23, 'W'} , {arr+24, 'X'}
, {arr+25, 'Y'} , {NULL, 'Z'} };
int main (void) {
struct list *root , *ptr;
root = arr;
for (ptr=root ; ptr; ptr = ptr->next ) {
printf( "-> %c" , ptr->ch );
}
printf( "\n" );
printf( "Swap\n" );
swap_odd_even ( &root);
for (ptr=root ; ptr; ptr = ptr->next ) {
printf( "-> %c" , ptr->ch );
}
printf( "\n" );
return 0;
}
In the following, every time swap_nodes is called another odd sinks to the last sunk odd. The evens are grouped together on each iteration and they bubble up to the end of the list. Here is an example:
/*
[0]-1-2-3-4-5
1-[0-2]-3-4-5
1-3-[0-2-4]-5
1-3-5-[0-2-4]
*/
#include <stdio.h>
#include <stdlib.h>
#define LIST_LENGTH 10
struct node{
int id;
struct node *next;
};
void print_list(struct node *current)
{
while(NULL != current){
printf("node id = %d\n",current->id);
current = current->next;
}
printf("Done\n");
}
struct node *swap_nodes(struct node *head_even, struct node *tail_even, struct node *next_odd)
{
tail_even->next = next_odd->next;
next_odd->next = head_even;
return next_odd;
}
struct node *reorder_list(struct node *head)
{
struct node *head_even;
struct node *tail_even;
struct node *next_odd;
struct node *last_odd;
if(NULL == head->next){
return head;
}
head_even = head;
tail_even = head;
next_odd = head->next;
last_odd = head->next;
head = swap_nodes(head_even, tail_even, next_odd);
if(NULL != tail_even->next){
tail_even = tail_even->next;
}
while (NULL != tail_even->next) {
next_odd = tail_even->next;
last_odd->next = swap_nodes(head_even, tail_even, next_odd);
last_odd = last_odd->next;
if(NULL != tail_even->next){
tail_even = tail_even->next;
}
}
return head;
}
int main(void)
{
int i;
struct node *head = (struct node *) malloc(LIST_LENGTH*sizeof(struct node));
struct node *mem = head;
if(NULL == head){
return -1;
}
struct node *current = head;
for(i=0;i<LIST_LENGTH-1;i++){
current->next = current + 1;
current->id = i;
current = current->next;
}
current->next = NULL;
current->id = i;
head = reorder_list(head);
print_list(head);
free(mem);
return 0;
}

What is wrong with my array of linked lists implementation as all elements get over-written?

I'm trying to implement a hash table as an array of linked lists. Currently I'm trying to have a simple hash table where the key is the index of the array and value is a singly linked list for implementing chaining.
This is the code that I've written so far:
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int value;
struct Node *next;
};
struct Node *hashtable[7];
int empty(int index)
{
if(hashtable[index]==NULL)
return 0;
return 1;
}
void addNode(int frame,struct Node **iter)
{
if(*iter==NULL)
*iter=malloc(sizeof(struct Node));
else
{
while((*iter)->next != NULL)
(*iter)=(*iter)->next;
(*iter)->next=malloc(sizeof(struct Node));
(*iter)=(*iter)->next;
}
(*iter)->value=frame;
(*iter)->next=NULL;
}
void print()
{
int i;
struct Node **iter;
for(i=0;i<7;i++)
{
iter=&hashtable[i];
while(*iter !=NULL)
{
printf("%d%s%d\n",(*iter)->value,"--",i);
(*iter)=(*iter)->next;
}
}
}
int main()
{
int i=0,count=7;
for(i=0;i<7;i++)
hashtable[i]=NULL;
i=empty(1);
printf("%d",i);
do
{
printf("Enter no:\n");
scanf("%d",&i);
struct Node** temp;
temp=&hashtable[i-1%7];
addNode(rand(),temp);
count--;
print();
} while(count > 0);
return 0;
}
When I'm calling print, I can only see one element added to one particular index, which is the last element that was added, what am I doing wrong here?
void add_node(int frame,struct Node **iter)
{
/* find (pointer to) NULL pointer at end of chain */
for ( ; *iter; iter = &(*iter)->next ) {;}
*iter = malloc(sizeof **iter );
(*iter)->value = frame;
(*iter)->next = NULL;
}

Linked list in C, is the list being constructed correctly?

I'm trying to implement a linked list abstraction, however I am running into problems. Once I create the linked list and add elements to it. When I print the list it only prints the first element in it in an infinite loop fashion, meaning that either the first element is linked to itself or the print function is incorrect. However, I can't find the problem, could someone help?
The following is the list abstraction:
typedef struct _friend {
char *firstname;
char *lastname;
char birthdate[9];
} friend;
typedef struct _node {
friend *value;
struct _node *next;
} node;
typedef struct _linkedlist {
node *head;
} linkedlist;
The program must follow this abstraction, as it is part of something bigger.
The following are the functions that should print the list and add a node to the beginning of the list:
/* addHead
*
* This function takes two parameters - a linked list and a friend.
* This creates a node for the linked list and connects the friend to the
* node. Then it adds the node to the head of the linked list.
*/
void addHead(linkedlist *llist, friend *f)
{
// create a node and put the friend in it
node *n = (node *)malloc(sizeof(node));
n->value = f;
n->next = NULL;
// if the list is empty
if (llist == NULL)
{
// this link is the entire list
llist->head = n;
printf("adding friend to null list\n");
}
// if the list is not empty
else
{
// make the new link's next pointer point to
// the first link in the list
n->next = llist->head;
printf("adding %s to head\n", n->value->firstname);
// make the head pointer point to the new link
llist->head = n;
}
}
/*
* printList
*
* This steps down through each of the nodes in a linked list and
* prints out the information stored in the friend to which the node points.
* Instead of automatically printing to the screen, it prints to the
* file pointer passed in. If the programmer wants to print to the screen,
* he/she will pass in stdout.
*/
void printList(linkedlist *llist,FILE *fp)
{
node *n;
friend *f;
// for each node, print out the friend attached to it
for(n = llist->head; n != NULL ; n = llist->head->next)
{
// assign f to the friend of the right node
f = n->value;
// print the friend out
fprintf(fp,"%s %s: %s\n",
f->firstname, f->lastname, f->birthdate);
}
}
Thank You
The for loop in printList isn't quite right:
for(n = llist->head; n != NULL ; n = llist->head->next)
This should read:
for(n = llist->head; n != NULL ; n = n->next)
Otherwise from the second iteration onwards, n gets set to the same value every single time.
The following isn't related to the problem you're having, but I thought I'd mention it anyway. In the following code:
if (llist == NULL)
{
// this link is the entire list
llist->head = n;
printf("adding friend to null list\n");
}
if llist == NULL, the llist->head = n will segfault.
With the current signature of addHead(), there's not a lot you can do if llist is NULL (other than printing an error message and bailing out).
If instead you meant to check whether llist->head is NULL, you don't need to do that since the else block already handles that correctly.
Try:
void printList(linkedlist *llist,FILE *fp)
{
node *n;
friend *f;
// for each node, print out the friend attached to it
for(n = llist->head; n != NULL ; n = n->next)
{
// assign f to the friend of the right node
f = n->value;
// print the friend out
fprintf(fp,"%s %s: %s\n",
f->firstname, f->lastname, f->birthdate);
}
}
I have done the following to your program:
slightly modified the friend structure. Declared firstname and lastname as arrays for convenience.
Wrote a main() which calls other functions
error checking in addHead()
added create_friend() function which creates friend struct
added freeList() to release the memory which was malloc()'ed
corrected looping error in your print function
So here it goes..
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _friend {
char firstname[10];
char lastname[10];
char birthdate[9];
} friend;
typedef struct _node {
friend *value;
struct _node *next;
} node;
typedef struct _linkedlist {
node *head;
} linkedlist;
void addHead(linkedlist *llist, friend *f)
{
node *n = NULL;
if (( n = (node *)malloc(sizeof(node))) == NULL) {
printf("unable to allocate memory \n");
exit(1);
}
n->value = f;
n->next = NULL;
if (llist == NULL) {
llist->head = n;
printf("adding friend to null list\n");
} else {
n->next = llist->head;
printf("adding %s to head\n", n->value->firstname);
llist->head = n;
}
return;
}
void printList(linkedlist *llist)
{
node *n;
friend *f;
if (llist->head == NULL) {
printf("Empty list \n");
return;
}
for(n = llist->head; n != NULL ; n = n->next) {
f = n->value;
printf("%s %s %d \n", f->firstname, f->lastname, f->birthdate);
}
return;
}
friend * create_friend(char *fn, char *ln, char *dob)
{
friend *fp = NULL;
if ((fp = malloc(sizeof(friend))) == NULL) {
printf("unable to allocate memory \n");
exit(1);
}
strcpy(fp->firstname, fn);
strcpy(fp->lastname, ln);
strcpy(fp->birthdate, dob);
return fp;
}
void freeList(linkedlist *llist)
{
node *cur = llist->head;
node *prev = cur;
friend *f;
while (cur != NULL) {
prev = cur;
cur = cur->next;
f = prev->value;
printf("freeing .. %s %s %d \n", f->firstname, f->lastname, f->birthdate);
free(prev->value);
free(prev);
}
return;
}
int main(void)
{
linkedlist ll;
friend *f;
ll.head = NULL;
f = create_friend("firstname1", "lastname1", "12345678");
addHead(&ll, f);
f = create_friend("firstname2", "lastname2", "12345678");
addHead(&ll, f);
f = create_friend("firstname3", "lastname3", "12345678");
addHead(&ll, f);
printList(&ll);
freeList(&ll);
ll.head = NULL;
printList(&ll);
return 0;
}
Hope this helps!
Should be n = n ->next otherwise you're just getting the next of the head every time.

Resources