Click here to Skip to main content
14,426,260 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hallo everyone , i am supposed to write a program to insert integers into a sorted linked list. and then delete any element the user chooses to. in the code i am unable to insert elements into my linked list. can someone help me?


Thanks in advance

the code is
[C] sorted linked list - Pastebin.com[^]

What I have tried:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
 
struct node {
// int data;
int key;
struct node *next;
};
 
struct node* init(){
struct node *head =0;
 
return head;
 
}
 
int isempty(struct node * head){
 
if(head == NULL)
return 1;
else
return 2;
}
 
//display the list
void printList(struct node * head) {
 
struct node *ptr = head;
printf("\n");
int n;
n=isempty(head);
if(n == 1)
printf("list is empty");
 
//start from the beginning
while(ptr != NULL) {
printf("%d ",ptr->key);
ptr = ptr->next;
}
 
}
 
void create(struct node * head,int num) {
 
struct node * tmp = head;
struct node * prev = NULL;
struct node* new = malloc(sizeof(struct node));
new->key = num;
prev = tmp;
int n;
n=isempty(head);
if(n == 1)
head->next = new;
while(tmp != NULL && tmp->key < num){
prev = tmp;
tmp = tmp->next;
}
new->next = tmp;
if(prev !=NULL)
prev->next = new;
}
 
/* struct node *tmp;
tmp=(struct node *)malloc(sizeof(struct node ));
tmp->data=data;
tmp->link=start;
start=tmp;*/
 
//delete a link with given key
struct node* delete(struct node * head, int del) {
 
//start from the first link
struct node* current = head;
struct node* previous = NULL;
struct node* temp = NULL;
 
//if list is empty
int n;
n=isempty(head);
if(n == 1) {
printf("list is empty");
return NULL;
}
 
//navigate through list
while(current->key != del) {
if (current == head){
temp = head;
temp = temp->next;
free(head);
head = temp;
}
 
//if it is last node
if(current->next == NULL) {
 
return NULL;
} else {
//store reference to current link
previous = current;
//move to next link
current = current->next;
}
}
 
//found a match, update the link
if(current == head) {
//change first to point to next link
head = head->next;
} else {
//bypass the current link
previous->next = current->next;
}
 
return current;
}
 
int main() {
 
int op;
int num;
struct node* head;
head=init();
 
do{
printf("\n Menu \n 1.Insert \n 2.delete element \n 3.display List \n 4. end program ");
printf("n \n \n please enter an option : ");
scanf("%d",&op);
 
switch (op) {
case 1:
printf("Enter data:");
scanf("%d",&num);
create(head, num);
break;
case 2:
printf("Enter data:");
scanf("%d",&num);
delete(head,num);
break;
case 3:
 
printList(head);
break;
case 4:
free(head);
exit(0);
 
default:
printf("\n enter an option : ");
}
}while(1);
 
}
Posted
Updated 26-Nov-18 11:24am
v3
Comments
jeron1 25-Nov-18 17:25pm
   
Could you post the code in the 'What have I tried' portion, and please include the code tags.
Member 14066698 25-Nov-18 17:46pm
   
i have done it
Rate this:
Please Sign up or sign in to vote.

Solution 2

I'm showing you some working code. Missing parts are left as exercise.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct node
{
  int key;
  struct node * next;
};

// init and isempty aren't really needed

// shows all the items of the list
void show( struct node * head )
{
  struct node * ptr = head;
  if ( ! ptr )
  {
    printf("(empty)");
  }
  else
  {
    while ( ptr )
    {
      printf(" %d ", ptr->key);
      ptr = ptr->next;
    }
  }
  printf("\n");
}

// creates a new node and inserts it into the list, maintaining the order
void insert(struct node ** phead, int key )
{
  struct node * new;
  struct node * cur = *phead;
  struct node * prev = NULL;

  new = (struct node *) malloc( sizeof (*new) );
  assert(new);
  new->key = key;
  new->next = NULL;

  while ( cur  && cur->key < key)
  {
    prev = cur;
    cur = cur->next;
  }

  if ( cur )
    new->next = cur;

  if ( prev )
    prev->next = new;
  else
    *phead=new;
}

// removes all the nodes, freeing the allocated memory
void clear(struct node * head)
{
  while ( head )
  {
    struct node * ptr = head;
    head = head->next;
    free(ptr);
  }
}

enum
{
  INSERT = 1,
  DELETE,
  SHOW,
  TERMINATE
};

int main()
{
  int option;
  struct node * head = NULL;
  do
  {
    printf("\n %d.Insert\n %d.Delete\n %d.Show\n %d Terminate\n", INSERT, DELETE, SHOW, TERMINATE);
    printf("\n Please enter na option: ");
    if ( scanf("%d", &option) != 1) continue;
    switch (option)
    {
    case INSERT:
      {
        int key;
        printf("Please enter data: ");
        if ( scanf("%d", &key) == 1)
          insert( &head, key);
      }
      break;
    case DELETE:
      printf("Left as exercise\n");
      break;
    case SHOW:
      show(head);
      break;
    case TERMINATE:
      clear(head);
      break;
    default:
      printf("Please enter an allowed option\n");
    }

  } while ( option != TERMINATE);
}
   
Rate this:
Please Sign up or sign in to vote.

Solution 1

Compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
int Double(int value)
   {
   return value * value;
   }

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

Learn to indent properly your code, it show its structure and it helps reading and understanding. It also helps spotting structures mistakes.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

struct node {
    // int data;
    int key;
    struct node *next;
};

struct node* init(){
    struct node *head =0;

    return head;

}

int isempty(struct node * head){

    if(head == NULL)
        return 1;
    else
        return 2;
}

//display the list
void printList(struct node * head) {

    struct node *ptr = head;
    printf("\n");
    int n;
    n=isempty(head);
    if(n == 1)
        printf("list is empty");

    //start from the beginning
    while(ptr != NULL) {
        printf("%d ",ptr->key);
        ptr = ptr->next;
    }

}

void create(struct node * head,int num) {

    struct node * tmp = head;
    struct node * prev = NULL;
    struct node* new = malloc(sizeof(struct node));
    new->key = num;
    prev = tmp;
    int n;
    n=isempty(head);
    if(n == 1)
        head->next = new;
    while(tmp != NULL && tmp->key < num){
        prev = tmp;
        tmp = tmp->next;
    }
    new->next = tmp;
    if(prev !=NULL)
        prev->next = new;
}

/* struct node *tmp;
tmp=(struct node *)malloc(sizeof(struct node ));
tmp->data=data;
tmp->link=start;
start=tmp;*/

//delete a link with given key
struct node* delete(struct node * head, int del) {

    //start from the first link
    struct node* current = head;
    struct node* previous = NULL;
    struct node* temp = NULL;

    //if list is empty
    int n;
    n=isempty(head);
    if(n == 1) {
        printf("list is empty");
        return NULL;
    }

    //navigate through list
    while(current->key != del) {
        if (current == head){
            temp = head;
            temp = temp->next;
            free(head);
            head = temp;
        }

        //if it is last node
        if(current->next == NULL) {

            return NULL;
        } else {
            //store reference to current link
            previous = current;
            //move to next link
            current = current->next;
        }
    }

    //found a match, update the link
    if(current == head) {
        //change first to point to next link
        head = head->next;
    } else {
        //bypass the current link
        previous->next = current->next;
    }

    return current;
}

int main() {

    int op;
    int num;
    struct node* head;
    head=init();

    do{
        printf("\n Menu \n 1.Insert \n 2.delete element \n 3.display List \n 4. end program ");
        printf("n \n \n please enter an option : ");
        scanf("%d",&op);

        switch (op) {
        case 1:
            printf("Enter data:");
            scanf("%d",&num);
            create(head, num);
            break;
        case 2:
            printf("Enter data:");
            scanf("%d",&num);
            delete(head,num);
            break;
        case 3:

            printList(head);
            break;
        case 4:
            free(head);
            exit(0);

        default:
            printf("\n enter an option : ");
        }
    }while(1);

}

Professional programmer's editors have this feature and others ones such as parenthesis matching and syntax highlighting.
Notepad++ Home[^]
ultraedit[^]
-----
Quote:
in the code i am unable to insert elements into my linked list. can someone help me?

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

The downside of this solution:
- It is a DIY, you are the one tracking the problem and finding its roots, which lead to the solution.
The upside of this solution:
- It is also a great learning tool because it show you reality and you can see which expectation match reality.

secondary effects
- Your will be proud of finding bugs yourself.
- Your learning skills will improve.

You should find pretty quickly what is wrong.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

1.11 — Debugging your program (stepping and breakpoints) | Learn C++[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100