Thread: Linked List (Create, Insert sorted, Remove duplicates)

  1. #1
    Registered User
    Join Date
    Mar 2014
    Posts
    15

    Linked List (Create, Insert sorted, Remove duplicates)

    1) I am require to create a function to requests a list of numbers from the user, terminated by a sentinel value of ‘-1’.

    2) Write a C function insertSorted() that adds a node into an existing linked list, maintainthe list values in ascending sorted order.
    For example, given the existing list of numbers stored in a linked list:
    1 2 3 6 8 9 15
    calling insertSorted() with a value of 11 will result in the following linked list:
    1 2 3 5 6 8 9 11 15
    Return:
    The value 11 was added at index 7

    3) Write a C function removeDuplicates() that removes all duplicate values from a linked
    list of numbers.
    For example, given a linked list:
    1 2 3 3 5 6 6 6 8 9 11 11 15 15
    Result:
    1 2 3 5 6 8 9 11 15
    4 numbers were removed from the list

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    typedef struct _listnode{
        int item;
        struct _listnode *next;
    } ListNode;
    
    
    typedef struct _linkedlist{ 
     ListNode *head; 
      ListNode *tail; 
     int size; 
    } LinkedList; 
    
    
    
    
    
    
    int insertNode(LinkedList *ll, int index, int value);
    int removeNode(LinkedList *ll, int index);
    void printList(LinkedList *ll);
    ListNode * findNode(LinkedList *ll, int index);
    
    
    int main(){ 
    	LinkedList l;
     
     LinkedList ll; 
     LinkedList *ptr_ll; 
     
     insertNode(&ll, 0, 100); 
     printList(&ll); 
     printf("%d nodes\n", ll.size); 
     removeNode(&ll, 0); 
     
     ptr_ll = (LinkedList *)malloc(sizeof(LinkedList)); 
     insertNode(ptr_ll, 0, 100); 
     printList(ptr_ll); 
     printf("%d nodes\n", ptr_ll->size); 
     removeNode(ptr_ll, 0); 
    }
    
    
    void printList(LinkedList *ll){
        
        ListNode *temp = ll->head;
        
        if (temp == NULL)
            return;
        
        while (temp != NULL){
            printf("%d ", temp->item);
            temp = temp->next;
        }
    }
    int insertNode(LinkedList *ll, int index, int value){
        
        ListNode *pre, *cur;
        
        if (ll == NULL || index < 0 || index > ll->size + 1)
            return -1;
        
        // If empty list or inserting first node, need to update head pointer
        if (ll->head == NULL || index == 0){
            cur = ll->head;
            ll->head = (ListNode *) malloc(sizeof(ListNode));
            
            if (ll->size == 0)
                ll->tail = ll->head;
            
            ll->head->item = value;
            ll->head->next = cur;
            ll->size++;
            return 0;
        }
        
        // Inserting as new last node
        if (index == ll->size){
            pre = ll->tail;
            cur = pre->next;
            pre->next = (ListNode *) malloc(sizeof(ListNode));
            ll->tail = pre->next;
            pre->next->item = value;
            pre->next->next = cur;
            ll->size++;
            return 0;
        }
        
        // Find the nodes before and at the target position
        // Create a new node and reconnect the links
        if ((pre = findNode(ll, index-1)) != NULL){
            cur = pre->next;
            pre->next = (ListNode *) malloc(sizeof(ListNode));
            pre->next->item = value;
            pre->next->next = cur;
            ll->size++;
            return 0;
        }
        
        return -1;
    }
    
    
    int removeNode(LinkedList *ll, int index){
        
        ListNode *pre, *cur;
        
        // Highest index we can remove is size-1
        if (ll == NULL || index < 0 || index >= ll->size)
            return -1;
        
        // If removing first node, need to update head pointer
        if (index == 0){
            cur = ll->head->next;
            free(ll->head);
            ll->head = cur;
            ll->size--;
            
            if (ll->size == 0)
                ll->tail = 0;
            
            return 0;
        }
        
        // Find the nodes before and after the target position
        // Free the target node and reconnect the links
        if ((pre = findNode(ll, index-1)) != NULL){
            
            // Removing the last node, update the tail pointer
            if (index == ll->size - 1){
                ll->tail = pre;
                free(pre->next);
                pre->next = NULL;
            }
            else{
                cur = pre->next->next;
                free(pre->next);
                pre->next = cur;
            }
            ll->size--;
            return 0;
        }
        
        return -1;
    }
    
    
    ListNode * findNode(LinkedList *ll, int index){
        
        ListNode *temp;
        
        if (ll == NULL || index < 0 || index >= ll->size)
            return NULL;
        
        temp = ll->head;
        
        if (temp == NULL || index < 0)
            return NULL;
        
        while (index > 0){
            temp = temp->next;
            if (temp == NULL)
                return NULL;
            index--;
        }
        
        return temp;
    }
    I tried to run the code, but it keeps on terminating without running and gives no error messages. Can anyone enlighten me?

  2. #2
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    Well, I don't know if it will make your program work as intended, but I know why your program is crashing and how to fix it. You're not initialising your linked list (in both instances).

    Question A) at line 33, what are the values of ll.size, ll.head, ll.tail?
    Question B) at line 40 (before the function call), what are the values of ptr_ll->size, ptr_ll->head and ptr_ll->tail?

  3. #3
    Registered User
    Join Date
    Mar 2014
    Posts
    15
    I gets errors by having this code. Can anyone teach me how to write the proper code to create a linked list from user's input?

    Code:
    /* Creates a linked list, adds and removes nodes and reverses list */
    
    
    #include <stdlib.h>
    #include <stddef.h>
    #include <stdio.h>
    
    
    typedef bool;
    #define false 0
    #define true 1 
    
    
    
    
    typedef struct node {
        int value;
        struct node *next;
    } node;
    
    
    node *head = NULL;    //Contains entire list
    node *current = NULL;  //Last item currently in the list
    
    
    // Initialize list with input value
    struct node* create_list(int input)
    {  
        node* ptr;
    
    
        printf("Creating a LinkedList with head node =  %d\n", input);
        ptr = (node*)malloc(sizeof(node)); // Allocating 8 bytes of memory for type node pointer
    
    
        if (ptr == NULL) // Would occur is malloc can't allocate enough memory
        {
            printf("Node creation failed \n");
            return NULL;
        }
    
    
        ptr->value = input;
        ptr->next = NULL;
        head = current = ptr;
    
    
        return ptr;
    }
    
    
    // Add input value to the end of the list
    struct node* add_to_end(int input)
    {
        node* ptr;
    
    
        if (head == NULL)
        {
            return create_list(input);
        }
    
    
        ptr = (struct node*)malloc(sizeof(struct node));
    
    
        if (ptr == NULL)
        {
            printf("Node creation failed \n");
            return NULL;
        }
        else
        {
            ptr->value = input;
            ptr->next = NULL;    // End value in list should have NULL next pointer
            current -> next = ptr; // Current node contains last value information
            current = ptr;
        }
    
    
        printf("%d Added to END of the LinkedList.\n", input);
        return head; 
    }
    // Add input value to the head of the list
    struct node* add_to_front(int input)
    {
        node* ptr;
    
    
        if (head == NULL)
        {
            return create_list(input);
        }
    
    
        ptr = (struct node*)malloc(sizeof(struct node));
        if (ptr == NULL)
        {
            printf("Node creation failed \n");
            return NULL;
        }
        else
        {
            ptr->value = input;
            ptr->next = head;  // Point next value to the previous head
            head = ptr;  
        }
    
    
        printf("%d Added to HEAD of the LinkedList.\n", input);
        return head;
    }
    
    
    // Return the number of items contained in a list
    int size_list(node* ptr)
    {
        int index_count = 0;
    
    
        while (ptr != NULL)
        {
            ++index_count;
            ptr = ptr->next;
        }
    
    
        return index_count;
    }
    
    
    // Add an input value at a user-specified index location in the list (starting from 0 index)
    struct node* add_to_list(int input, int index)
    {
        node* ptr_prev = head;
        node* ptr_new;
    
    
        int index_count;         // Used to count size of list
        int index_track = 1;     // Used to track current index
    
    
        ptr_new = (struct node*)malloc(sizeof(struct node));
    
    
        // Check that list exists before adding it in
        if (head == NULL)
        {
            if (index == 0)   // Create new list if 0 index is specified
            {
                add_to_front(input);
            }
            else
            {
                printf("Could not insert '%d' at index '%d' in the LinkedList because the list has not been initialized yet.\n", input, index);
                return NULL;
            }
        }
    
    
        // Count items in list to check whether item can added at specified location
        if ((index_count = size_list(head)) < index)
        {
            printf("Could not insert '%d' at index '%d' in the LinkedList because there are only '%d' nodes in the LinkedList.\n", input, index, index_count);
            return NULL;
        }
    
    
        //Go through list -- stop at item before insertion point
        while (ptr_prev != NULL)
        { 
            if (index == 0)  // Use add_to_front function if user-specified index is 0 (the head of the list)
            {
                add_to_front(input);
                return head;
            }
    
    
            if ((index_track) == index)  
            {       
                break;
            }
    
    
            ptr_prev = ptr_prev ->next;
            ++index_track;
        }
    
    
        ptr_new ->next = ptr_prev ->next;   // Change the new node to point to the original's next pointer
        ptr_new->value = input;
        ptr_prev ->next = ptr_new;  // Change the original node to point to the new node
    
    
        return head;
    }
    
    
    // Verify if the list contains an input value and return the pointer to the value if it exists
    struct node* search_list(int input, struct node **prev)
    {
        node* ptr = head;
        node* temp = (node*)malloc(sizeof(node));
        bool found = false;
    
    
        // Search if value to be deleted exists in the list
        while (ptr != NULL)
        {
            if(ptr->value == input)
            {
                found = true;
                break;
            }
            else
            {
                temp = ptr;
                ptr = ptr ->next;
            }
        }
    
    
        // If the value is found in the list return the ptr to it
        if(found == true)
        {
            if(prev)
                *prev = temp;
    
    
            return ptr;
        }
        else
        {
            return NULL;
        }
    }
    
    
    // Remove an input value from the list
    struct node* remove_from_list(int input)
    {
        int num;
    	printf("Number to be deleted");
    	scanf("%d",&num);
    	node* prev = NULL; // list starting from one item before value to be deleted
        //node* del = NULL;  // pointer to deleted value
    	node* del = scanf("%d",&num);
    
    
        // Obtain pointer to the list value to be deleted
        del = search_list(input, &prev);
    
    
        if(del == NULL)
        {
            printf("Error: '%d' could not be deleted from the LinkedList because it could not be found\n");
            return NULL;
        }
        else
        {
            if (prev != NULL)
            {
                prev->next = del->next;
            }
    
    
            if (del == current)  // If item to be deleted is last in list, set the current last item as the item before deleted one
            {
                current = prev;
            }
            else if (del == head) // If item to be deleted is the head of the list, set the new head as the item following the deleted one
            {
                head = del ->next;
            }
    
    
            return head;
        }
    }
    
    
    
    
    // Print the list to the console
    void print_list()
    {
        node* ptr = head;
    
    
        printf("------------------------------\n");
        printf("PRINTING LINKED LIST\n");
        while (ptr != NULL)
        {
            printf("%d\n", ptr->value);
            ptr = ptr->next;
        }
    
    
        printf("------------------------------\n");
    }
    
    
    int main()
    {
        int i;
    
    
        for (i = 3; i > 0; --i)
        {
            add_to_front(i);
        }
    
    
        for (i= 4; i < 7; ++i)
        {
            add_to_end(i);
        }
    
    
        add_to_list(4,9); //test function error message
        add_to_list(4,1); 
        print_list(); 
        remove_from_list(3); 
        print_list();
        print_list();
        add_to_list(10,0);
        print_list();
        getchar();
    }
    Linked List (Create, Insert sorted, Remove duplicates)-1-jpg

  4. #4
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    What are you doing? Randomly copying other people's code and hoping it works? Why are head and current now global values?

    By the way, it compiles fine for me (ignoring the warnings)... get rid of visual studio until you know more about how things work...

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    I gets errors by having this code.
    So you found random code on the net and are trying to get someone to fix it up for you?

    I don't know whether it's sad or funny that you copied that code while completely disregarding the very detailed corrections offered below it.

    Can anyone teach me how to write the proper code to create a linked list from user's input?
    It's probably not even worth the time, but I'll give you a chance to start clean here. First step - put the code aside, and explain in words how you understand linked lists to work.

  6. #6
    Registered User
    Join Date
    Mar 2014
    Posts
    15
    How to compare eg. Linked list stores : 1 2 3. Then user input 2. How could I compare the user input '2' with the linked list items? So I could possibly slot '2' before '3' in the linked list to make the linked list have 4 items? I tried by comparing the linked list item to the user input but could not successfully do so. Could you teach me how to do it? This time round, I did it myself.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    typedef struct _listnode{
        int item;
        struct _listnode *next;
    } ListNode;
    
    
    typedef struct _linkedlist{
        int size;
        ListNode *head;
        ListNode *tail;
    } LinkedList;
    
    
    void printList(LinkedList *ll);
    ListNode * findNode(LinkedList *ll, int index);
    int insertNode(LinkedList *ll, int index, int value);
    int removeNode(LinkedList *ll, int index);
    
    
    int main(){
        
        LinkedList l;
    	int i=0,j=0,counter=0;
    	int choice;
        LinkedList *ll; int index; int value;
        l.head = 0;
        l.size = 0;
    
    
    	printf("1. createLinkedList()\n"); 
    	printf("2. insertSorted()\n"); 
    	printf("3. removeDuplicates()\n"); 
    	do { 
    		printf("\nChoose an option : "); 
    		scanf("%d", &choice); 
    		fflush(stdin); 
    	switch (choice) { 
    			
    		case 1:
    			printf("Enter list : ");
    			scanf("\n%d", &i);
    			while(i!=-1) {
    				insertNode(&l, j, i);
    				j++;
    				counter++;
    				scanf("\n%d", &i); 
    						}
    			printf("Printing list: \n");
    			printList(&l);
    			printf("\ncounter : %d",counter);
    			printf("\n");
    			break;
    
    
    		case 2:	
    			printf("Enter number to insert : ");
    			scanf("\n%d", &i);
    			insertNode(&l, j, i);
    			j++;
    			counter++;
    			printf("Printing list: \n");
    			printList(&l);
    			printf("\ncounter : %d",counter);
    			printf("\n");
    			break;
    
    
    		case 3:
    			removeNode(ll, index);
    			break;
    		
    		} 
    	} while (choice < 4); 
        return 0;
    }
    
    
    void printList(LinkedList *ll){
        
        ListNode *temp = ll->head;
        
        if (temp == NULL)
            return;
        
        while (temp != NULL){
            printf("%d ", temp->item);
            temp = temp->next;
        }
    }
    
    
    ListNode * findNode(LinkedList *ll, int index){
        
        ListNode *temp;
        
        if (ll == NULL || index < 0 || index >= ll->size)
            return NULL;
        
        temp = ll->head;
        
        if (temp == NULL || index < 0)
            return NULL;
        
        while (index > 0){
            temp = temp->next;
            if (temp == NULL)
                return NULL;
            index--;
        }
        
        return temp;
    }
    
    
    int insertNode(LinkedList *ll, int index, int value){
        
        ListNode *pre, *cur ;
        
        if (ll == NULL || index < 0 || index > ll->size + 1)
            return -1;
        
        // If empty list or inserting first node, need to update head pointer
        if (ll->head == NULL || index == 0){
            cur = ll->head;
            ll->head = (ListNode *)malloc(sizeof(ListNode));
            
            if (ll->size == 0)
                ll->tail = ll->head;
            
            ll->head->item = value;
            ll->head->next = cur;
            ll->size++;
            return 0;
        }
        
        // Inserting as new last node
        if (index == ll->size){
            pre = ll->tail;
            cur = pre->next;
            pre->next = (ListNode *)malloc(sizeof(ListNode));
            ll->tail = pre->next;
            pre->next->item = value;
            pre->next->next = cur;
            ll->size++;
            return 0;
        }
    
    
        // Find the nodes before and at the target position
        // Create a new node and reconnect the links
        if ((pre = findNode(ll, index-1)) != NULL){
    
    
    		 ll->head->item = value;
            ll->head->next = cur;
    		if (ll->head->item) > (value)) {
    			ll->head->item = value;
    			ll->head->next = ll->head;
    		}
    
    
            /*cur = pre->next;
            pre->next = (ListNode *)malloc(sizeof(ListNode));
            pre->next->item = value;
            pre->next->next = cur;
            ll->size++; */
            //return 0;
       // }
        
        return -1;
    }
    
    
    int removeNode(LinkedList *ll, int index){
        
        ListNode *pre, *cur;
        
        // Highest index we can remove is size-1
        if (ll == NULL || index < 0 || index >= ll->size)
            return -1;
        
        // If removing first node, need to update head pointer
        if (index == 0){
            cur = ll->head->next;
            free(ll->head);
            ll->head = cur;
            ll->size--;
            
            if (ll->size == 0)
                ll->tail = 0;
            
            return 0;
        }
        
        // Find the nodes before and after the target position
        // Free the target node and reconnect the links
        if ((pre = findNode(ll, index-1)) != NULL){
            
            // Removing the last node, update the tail pointer
            if (index == ll->size - 1){
                ll->tail = pre;
                free(pre->next);
                pre->next = NULL;
            }
            else{
                cur = pre->next->next;
                free(pre->next);
                pre->next = cur;
            }
            ll->size--;
            return 0;
        }
        
        return -1;
    }
    Linked List (Create, Insert sorted, Remove duplicates)-1212-jpg

  7. #7
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    This time round, I did it myself.
    I do not believe you. Nor will I help you engage in academic dishonesty or plagiarism. I gave you a chance to start clean - but that didn't happen, so I'm done here.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorted Linked list Help please
    By Tryhard in forum C Programming
    Replies: 9
    Last Post: 04-02-2013, 06:03 PM
  2. Replies: 2
    Last Post: 10-31-2012, 02:31 AM
  3. removing duplicates from a linked list
    By brianptodd in forum C++ Programming
    Replies: 2
    Last Post: 10-27-2003, 10:27 PM
  4. sorted linked list
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 02-03-2002, 09:11 PM
  5. Deleting duplicates in a linked list
    By tetramethrin in forum C++ Programming
    Replies: 6
    Last Post: 10-28-2001, 07:37 PM

Tags for this Thread