Visual Studio has suddenly stopped working (Linked List Code) - c

every one
I've got an issue when working with linked list function. Visual Studio has just suddenly stopped working. The following is my code:
#include<stdio.h>
#include<stdlib.h>
typedef struct _listnode
{
int item;
struct _listnode* next;
}Listnode;
void printlist(Listnode *head);
void main(){
Listnode *head, *temp;
int i = 0;
head = malloc(sizeof(Listnode));
temp = head;
for(;i<3;i++){
temp->item = i;
if (i != 2){
temp->next = malloc(sizeof(Listnode));
temp = temp->next;
}
else
temp = NULL;
}
printlist(head);
}
void printlist(Listnode *head){
if (head == NULL)
printf("Your list is empty");
while(head != NULL){
printf(" %d ",head->item);
head = head->next;
}
printf(" \n ");
}
Output:
0 1 2
And then it has displayed the following message
Could anyone tell me exactly what was going on? Any help will be appreciated much. Thank you
Best Regards

You never set the final link pointer to NULL when creating the list. You set temp to null when, presumably you want to set temp->next to null instead.
It is a lot more "robust" to keep the list in a valid state after every transaction. Right now, you depend on an if statement inside the loop to convert the last iteration into an "end the list" operation instead of an "add to the list". If someone were to change the for loop limits without changing that if statement to match, you'd be back to a broken list again. Try something like this:
Listnode *head = NULL; /* start with an empty list */
Listnode *tail = NULL;
for (i=0; i<3; ++i)
{
ListNode *temp = malloc(sizeof(Listnode));
temp->item = i;
temp->next = NULL;
if (head == NULL)
head = tail = temp;
else
{
tail->next = temp;
tail = temp;
}
}
There is still an if statement in the loop, but it is instructive. The loop body is how you might write a function to push a new list entry onto the end of a singly-linked list. Keeping both a head and tail pointer makes this efficient, avoiding a loop to find the end of the list.
The point is that no matter how the loop is modified, the loop will add one entry per iteration, and the list will be valid at the end of each iteration.

Related

Linked List Reversal has errors

In our class right now we're covering nodes and linked lists, and are working on our first linked list program.
We've been given the following guidelines by the teacher:
Make sure your main function will accept 10 characters from STDIN and create a linked list with those characters (so your nodes will have a char member). Then, add an additional function called reverse. The purpose of the reverse function will be to create a copy of the linked list with the nodes reversed. Finally, print off the original linked list as well as the reversed linked list.
I've gotten it all written out, and I've compiled it with no errors - but the program doesn't work as intended, and I'm not entirely sure why. I'm sure it has something to do with how I've set up the pointers to "walk" the nodes - as the debug I put in shows it looping twice per user input letter. Specifications are that we're only supposed to use one function, and we pass a Node* to the function, and it returns the same. The function cannot print out anything - only make the second list that is a reverse of the first.
Any help would be greatly appreciated, I'm not terribly good at this yet and I'm sure I've made some rather silly mistakes.
#include <stdio.h>
#include <stdlib.h>
//struct declaration with self-reference to make a linked list
struct charNode {
char data;
struct charNode *nextPtr;
struct prevNode *prevPtr;
};
typedef struct charNode Node; //makes Node an alias for charNode
typedef Node *NodePtr; //makes NodePtr an alias for a pointer to Node (I think?)
//function declaration for a reverse function
Node* reverse(Node *stPtr);
int main(void)
{
//main function takes 10 letters and puts them in a linked list
//after that, it calls the reverse function to create a reversed list of those characters
//lastly it prints both lists
NodePtr newNode = NULL;
char input;
Node* revStart;
unsigned int counter = 0;
printf("Enter 10 letters to make a list: ");
NodePtr currentPtr = NULL; //sets currentPointer to startNode.
NodePtr previousPtr = NULL; //set previousPointer to null to start
while(counter<= 10)
{
scanf("%c", &input); //gather next letter
NodePtr newNode = malloc(sizeof(Node)); //creates a new node
if (newNode != NULL) //checks to make sure the node was allocated correctly
{
newNode->data = input; //makes the new node's data == input
newNode->nextPtr = NULL; //makes the nextPtr of the newNode NULL
}
currentPtr = newNode; //sets currentPtr to the address of the newNode
if(previousPtr == NULL) { //first time around previousPtr == NULL
newNode->nextPtr = newNode;
previousPtr = newNode; //sets previousPtr to the address of the new node (1st time only)
} else { //afterwards, currentPtr won't be NULL
previousPtr->nextPtr = currentPtr; //last node's pointer points to the current node
previousPtr = newNode; //update previous pointer to the current node
}
++counter;
//debug
printf("\nLoop #%d\n", counter);
}
revStart = reverse(newNode);
puts("The list is: ");
while (newNode != NULL){
printf("%c --> ", newNode->data);
currentPtr = currentPtr->nextPtr;
}
puts("NULL\n");
}
//reversing the nodes
Node* reverse(Node *stPtr)
{
//make a new node
NodePtr currentPtr = stPtr->nextPtr; //get the next letter ready (this will point to #2)
NodePtr prevRevPtr = NULL; //previous reverse node pointer
Node* revStart;
for(unsigned int counter = 1; counter <= 10; ++counter)
{
NodePtr revNode = malloc(sizeof(Node));
if(revNode != NULL) //if reverseNode is allocated...
{
if(prevRevPtr = NULL) //if previousReversePointer = NULL it's the "first" letter
{
revNode->data = stPtr->data; //letter = current letter
revNode->nextPtr = NULL; //this is the "last" letter, so NULL terminate
prevRevPtr = revNode; //previousReversePointer is this one
}else //after the first loop, the previous ReversePointer will be set
{
revNode->data = currentPtr->data; //set it's data to the pointer's data
revNode->nextPtr = prevRevPtr; //reverseNode's pointer points to last node entered
currentPtr = currentPtr->nextPtr; //moves to next letter
prevRevPtr = revNode; //changes previous reverse node to current node
if(counter == 10)//on the last loop...
{
revStart = revNode; //set revStart as a pointer to the last reverse node
//which is technically the "first"
}
}
}
}
return revStart;
}
Assuming your list is properly wired from inception, reversing a double-linked list is basically this:
Node *reverse(Node *stPtr)
{
Node *lst = stPtr, *cur = stPtr;
while (cur)
{
Node *tmp = cur->nextPtr;
cur->nextPtr = cur->prevPtr;
cur->prevPtr = tmp;
lst = cur;
cur = tmp;
}
return lst;
}
That's it . All this does is walk the list, swapping pointers, and retaining whatever the last node processed was. When done correctly the list will still be end-terminated (first node 'prev' is null, last node 'next' is null, and properly wired between.
I strongly advise walking a list enumeration through this function in a debugger. With each iteration watch what happens to cur as it marches down the list, to the active node's nextPtr and prevPtr values as their swapped, and to lst, which always retains the last-node processed. It's the new list head when done.
Okay so we don't need to contend with no line breaks in commments:
Node *reverse(Node *list) {
Node *rev = NULL;
while (list) {
Node *elt = list; // pop from the list
list = list->next;
elt->next = rev; // push onto reversed list.
rev = elt;
}
return rev;
}
As you wrote in comments, you probably don't need to have a previous pointer; you can just create a singly linked list.
There are several issues in your code, including:
When malloc returns NULL, you still continue with the loop -- only part of the code is protected by the if that follows, but not the rest. You should probably just exit the program when this happens.
Your algorithm does not maintain a reference to the very first node, i.e. the place where the linked list starts. When you print the list you should start with the first node of the list, but instead you start with newNode, which is the last node you created, so obviously not much will be printed except that last node. Moreover, both other pointers you have, will also point to the last node (currentPtr, previousPtr) when the loop ends.
newNode->nextPtr = newNode; temporarily creates an infinite cycle in your list. This is resolved in the next iteration of the loop, but it is unnecessary to ever make the list cyclic.
In the reverse function you have if(prevRevPtr = NULL)... You should get a warning about that, because that is an assignment, not a comparison.
Some other remarks:
The reverse function unnecessarily makes distinction between dealing with the first node and the other nodes.
It is also not nice that it expects the list to have 10 nodes. It would be better to just rely on the fact that the last node will have a NULL for its nextPtr.
It is a common habit to call the first node of a linked list, its head. So naming your variables like that is good practice.
As you are required to print both the initial list and the reversed list, it would be good to create a function that will print a list.
As you need to create new nodes both for the initial list and for the reversed list, it would be good to create a function that will create a node for you.
(I know that your teacher asked to create only one function, but this is just best practice. If this doesn't fit the assignment, then you'll have to go with the malloc-related code duplication, which is a pitty).
As you defined the type NodePtr, it is confusing to see a mix of Node* and NodePtr in your code.
Your question was first not clear on whether the reversal of the list should be in-place or should build a new list without tampering with the initial list. From comments it became clear you needed a new list.
I probably didn't cover all problems with the code. Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
struct charNode {
char data;
struct charNode *nextPtr;
};
typedef struct charNode Node;
typedef Node *NodePtr;
NodePtr reverse(Node *stPtr);
void printList(Node *headPtr);
NodePtr createNode(int data, NodePtr nextPtr);
int main(void) {
NodePtr headPtr = NULL; // You need a pointer to the very first node
NodePtr tailPtr = NULL; // Maybe a better name for currentPtr
printf("Enter 10 letters to make a list: ");
for (int counter = 0; counter < 10; counter++) {
char input;
scanf("%c", &input);
NodePtr newNode = createNode(input, NULL);
if (headPtr == NULL) {
headPtr = newNode;
} else {
tailPtr->nextPtr = newNode;
}
tailPtr = newNode;
}
NodePtr revHeadPtr = reverse(headPtr);
puts("The list is:\n");
printList(headPtr);
puts("The reversed list is:\n");
printList(revHeadPtr);
}
void printList(NodePtr headPtr) {
while (headPtr != NULL) {
printf("%c --> ", headPtr->data);
// You can just move the head pointer: it is a variable local to this function
headPtr = headPtr->nextPtr;
}
puts("NULL\n");
}
NodePtr createNode(int data, NodePtr nextPtr) {
NodePtr newNode = malloc(sizeof(Node));
if (newNode == NULL) { // If malloc fails, exit the program
puts("Cannot allocate memory\n");
exit(1);
}
newNode->data = data;
newNode->nextPtr = nextPtr;
return newNode;
}
NodePtr reverse(NodePtr headPtr) {
NodePtr revHeadPtr = NULL;
while (headPtr != NULL) {
revHeadPtr = createNode(headPtr->data, revHeadPtr);
// You can just move the head pointer: it is a variable local to this function
headPtr = headPtr->nextPtr;
}
return revHeadPtr;
}

Reverse fuction for singly linked list isn't working as it should

we've given a task to reverse a singly linked list and for some reason i struggling with it
its reversing as it should ,but the head that should be the tail just disappears and i can't figure why, even after debugging
'''
void Reverse(struct node *head) {
struct node *last = NULL;
struct node *current = NULL;
struct node *temp = NULL;
current = head;
while (current->next != NULL) { //getting ptr to last item of the list
current = current->next;
last = current;
};
current = head; //resseting the current ptr back to the head of the list
while (current->next->next != NULL) { //getting the current ptr to one before the tail item
current = current->next;
};
temp = last;
while (last != head) {
if (current->next == last) {
last->next = current;
last = current;
current = head;
if (last == head) {
head->next = NULL;;
head->data = temp->data;
head->next = temp->next;
break;
};
};
};
};
'''
I can't completely follow the logic in your code. You find the last and the second last element, and I will assume that head is some dummy element that you always have (because otherwise, not checking if it is NULL is a problem). After that, I am not sure what happens. You "flip" the last two links if you are looking at the head you update it? (You don't need to set head->next to NULL before you update it two lines later; that doesn't do anything).
Did you want to move current from the head and down to the one before last somewhere in the loop? I think that would work, but you would get a quadratic time algorithm.
If we assume that head is a dummy, so it doesn't have any elements to worry about, and we just want its next pointer to point to the reversed links, you should be able to do something like this:
void reverse(struct node *head)
{
struct node *next = head->next;
head->next = 0;
while (next) {
struct node *next_next = next->next;
next->next = head->next;
head->next = next;
next = next_next;
}
}
In the while-loop you can think of the code as pushing next to the front of the list pointed to by head->next and popping it off the current list (by setting next to next_next. When you reach the end of the list, head->next points to all the links, in reversed order. (I haven't tested the code, but I belive it should work).
If head is not a dummy node, you have to handle the special case that it is NULL, and you have to move its value. It makes things trickier if you have to do the latter, especially if you want to use the list generically, where the user is allowed to allocate links, and you might not know what data is in them (beyond that they have a link embedded in them). I would go for having a dummy link if you can, it makes everything simpler, not just reversal.
Of course, with doubly-linked lists it gets simpler still:
#define swap_p(x,y) \
do { struct node *tmp = x; x = y; y = tmp; } while(0)
void reverse(node *dummy)
{
struct link *p = dummy;
do {
swap_p(p->prev, p->next);
p = p->prev;
} while (p != dummy);
}
but that might not be what you want.
Don't know if that helps, but I hope it does a little at least.

Difference between Node->next!=NULL and Node!=NULL in C

This function doesn't work if I make a modification in while condition and change temp != NULL to temp->next = NULL. Why is that?
void Print() {
printf("\n");
printf("The Library data is as follows: \n");
struct Node *temp = head; // where head is a global variable
printf("\n");
while (temp != NULL) {
printf("%25s", temp->name);
printf("%25s", temp->author);
temp = temp->next;
printf("\n");
}
}
Plus if I modify the while loop condition under else block, from temp1->next = NULL to temp1 != NULL, it doesn't work. Why is that?
void Insert(char q[50], char r[50]) {
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->next = NULL; // Since we are adding a node to the end, we are linking it to NULL.
strcpy(temp->name, q); // copying the contents of "q" to "temp->name"
strcpy(temp->author, r); // same
if (head == NULL) {
head = temp;
} else {
struct Node *temp1 = head;
while (temp1->next != NULL)
temp1 = temp1->next;
temp1->next = temp;
}
}
In the Print function, you want to enumerate all nodes in the list, and you want to handle an empty list (head = NULL) gracefully. Hence the loop iterates while (temp == NULL) and temp skips to the next node with temp = temp->next;.
In the Insert function, a new node is allocated and initialized. There is a special case for the empty list (head == NULL) where head just receives the pointer to the new node. Conversely, if the list is not empty, you want to find the last node of the list to append the new node by setting its next pointer to point to the new node. The loop iterates from the first to the last node, the test temp1->next != NULL succeeds if the node is not the last one. Hence temp points to the last node after the while loop and the new node can simply be appended with temp1->next = temp;.
Note the following remarks:
the prototype void Insert(char q[50], char r[50]) should be improved as int Insert(const char *name, const char *author) because:
the strings passed as arguments are not modified by the function
the argument names would be clearer
the array sizes specified are ignored by the compiler and seem inconsistent with the actual structure members.
the function can fail. It should at least return a success indicator.
memory allocation should be tested for success and failure should be reported
strcpy will cause undefined behavior if the arguments strings are too long.
There is no need to cast the return value of malloc in C.
Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
struct Node {
char name[50];
char author[50];
struct Node *next;
};
struct Node *head = NULL;
void Print(void) {
printf("\nThe Library data is as follows:\n\n");
struct Node *temp = head; // where head is a global variable
while (temp != NULL) {
printf("%25s %-25s\n", temp->name, temp->author);
temp = temp->next;
}
}
int Insert(const char *name, const char *author) {
struct Node *temp = malloc(sizeof(struct Node));
if (temp == NULL)
return -1;
temp->next = NULL;
snprintf(temp->name, sizeof(temp->name), "%s", name);
snprintf(temp->author, sizeof(temp->author), "%s", author);
if (head == NULL) {
head = temp;
} else {
struct Node *temp1 = head;
while (temp1->next != NULL)
temp1 = temp1->next;
temp1->next = temp;
}
return 0;
}
int main() {
if (Insert("Flowers for Algernon", "Daniel Keyes")
|| Insert("Blade Runner", "Philip K. Dick")
|| Insert("2001, a Space Odyssey", "Arthur C. Clarke")) {
printf("out of memory\n");
return 1;
}
Print();
return 0;
}
When change that to node->next in while loop its mean this loop loops while node->next is null so u miss last node of your linked array because this node's-next is null so loop is break in this time.And only write temp to your while u dont need temp != NULL this loop breaks when temp is null so only put
while(temp){
//your code
}
I hope this will be help you. :-)
In the first case You are traversing through the entire linked list.End of linked list is denoted by NULL pointer as per your code so while(temp!=NULL) is used.This will work with temp1->next!=NULL if there are more than 2 nodes by skipping the last one.
In second case you add new node to the end of the last node.So you have to use temp1->next!=NULL. so that the last node's next pointer can point to the newly added node.If you use temp!=NULL in this case, Then temp becomes NULL. So the next statement temp1->next=temp; cannot work.
If you make change in first case, it will only cause program to skip
printing the last node in the linked list.
If you make change in second case, this will cause your code to get
terminated (runtime error).
Its very simple
In function print() when you use while(temp->next!=null) then it will not print last
node because when pointer temp is at last node temp->next is null and while condition
become false and it come out of while loop.
In function insert() if you change while(temp1->next!=NULL) to while(temp1!=NULL) then
when it come from while loop temp1 points to null means no memory is allocated .
hence writing temp1->next in after while loop shows error as you cannot excess next
part of temp because memory is not allocated.
Hope this will help you!

Inserting to beginning of linked list (revisited)

I'm very new to coding in C (and therefore the silly exercise I am working on). I tried looking at this other solution to a similar question, but it seems like my coding strategy is different, and ultimately I would like to understand what is the problem with my code. I would greatly appreciate your input.
I have a linked list, a function that inserts a new node at the beginning of my list, a function that prints my linked list, and main function.
Unfortunately my knowledge of C is not good enough to understand why my function is not inserting at the beginning of the list. What is even more unfortunate is that this code does not crash.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} *Node_t;
void print_list(Node_t root) {
while (root) {
printf("%d ", root->data);
root = root->next;
}
printf("\n");
}
void add_to_list(Node_t *list, Node_t temp){
// check if list is empty
if ((*list)->next == NULL) {
// insert first element
(*list) = temp;
}
else {
temp->next = (*list);
(*list) = temp;
}
}
int main () {
int val1 = 4;
int val2 = 8;
int val3 = 15;
Node_t list = malloc(sizeof(struct Node));
Node_t temp1 = malloc(sizeof(struct Node));
Node_t temp2 = malloc(sizeof(struct Node));
Node_t temp3 = malloc(sizeof(struct Node));
temp1->data = val1;
temp1->next = NULL;
temp2->data = val2;
temp2->next = NULL;
temp3->data = val3;
temp3->next = NULL;
//Initialize list with some values
list->data = 0;
list->next = NULL;
/* add values to list */
add_to_list(&list,temp1);
add_to_list(&list,temp2);
add_to_list(&list,temp3);
print_list(list);
}
This code will only ever print the last node I have attempted to add to the list, therefore overwriting the previous nodes.
For example:
Running…
15
Debugger stopped.
Program exited with status value:0.
A single mistake in add_to_list() function:
if ((*list)->next == NULL) { // checks next of first is NULL not list is NULL
// to insert at first
should be just:
if ((*list) == NULL){ // You need to check list is NULL
Check working code
Why you were getting only 15 the last node (temp3) value?
Because in main you creates three temp nodes and initialized next of every node to NULL, including list node so in add_to_list() function if condition ((*list)->next == NULL) always evaluates true and list always initialized with temp node.

Linked Lists delete node at position N

EDIT: Figured out the problem. Also if you found this through google or another search engine here is where I went wrong and how to fix it.
My deleteNode() method was moving through the list properly with the correct temp and keeping the head untouched. Where I was going wrong was in what I was returning as the result of the method. I was returning either temp or newNode which is incorrect because it goes through the list until it finds defined position. Once it finds that defined position it it would reassign the ->next pointer to point to the next->next> pointer which is correct but again I was returning the wrong thing. Because we had moved through the list using temp/NewNode we lost the header and we were returning the position we found and whatever was still in the next positions of the list.
How we fix this is returning the head (which is what is passed into the method). The reason why this works is because we have to understand how LinkedLists work. The pointers of each node point to the next node. Ex. we have a linked list |A|| - |B|| - |C|| - |D|| - |E|| - |F||
If we want to delete Node C we move to node B using the temp pointer and then assign the B->next to temp->next->next Thus skipping over C node and assigning D node.
NOTE: (From what I know this does not actually free the memory of C node so it isn't best practice because you can cause memory leaks this way) You should use the free() method on the C node.
Here is the code I ended up using
struct node* DeleteNode(struct node* head, int pos) {
struct node* temp = head;
int length = LinkedListLength(temp);
int i;
if(pos <= 0 || pos > length){
printf("ERROR: Node does not exist!\n");
}else{
if(pos == 1){
head = head->next; //move from head (1st node) to second node
}else{
for(i = 1; i < pos-1; ++i){ //move through list
temp = temp->next;
}
temp->next = temp->next->next;
}
}
return head;
}
Hopefully that helps understand how I went out fixing it.
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
ORIGINAL POST
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
EDIT: Note: This is a homework assignment I have spent a few days (estimated 4 hours) programming it I am just stuck on this one part. You can view my attempt below
I've been able to insert and delete from begining/end however I can't seem to get my delete node at position N in linkedlist to work.
My psuedocode looks like this:
LinkedList: 1,3,5,7,9,23
Grab LinkedList
Create new struct node A = head
Move through linkedlist until
position
Assign node to node->next
return linkedlist
EXAMPLE INPUT
Node structure
int data;
struct node* next;
int values[] = {1,3,5,7,9,23};
struct node* llist = CreateList(values,6);
llist = DeleteNode(llist, 1);
llist = DeleteNode(llist, 5);
llist = DeleteNode(llist, 3);
Which should leave the llist with the values 3, 5, 9 once the code has been run However, It is replacing the first node with a 0
Actual Code:
struct node* DeleteNode(struct node* head, int pos) {
struct node* temp = head;
struct node* newNode = head;
int length;
int i;
printf("DeleteNode: position = %d \nBefore: ", pos);
PrintList(temp);
if(pos <= 0){ //node does NOT exist
printf("ERROR: Node does not exist!\n");
}else{ //node DOES exist
length = LinkedListLength(temp);
if(length < pos){ //if length < position Node does not exist
printf("ERROR: Node does not exist!\n");
}else{
if(pos == 0){
newNode = temp->next;
}else if(pos == 1){
newNode = temp->next;
}else{
for(i = 1; i < pos; i++){
printf("i = %d\n", i);
temp = temp->next;
newNode->next;
}
if(temp->next == NULL){
newNode = NULL;
}else{
newNode = temp->next;
}
}
printf("After: ");
PrintList(newNode);
printf("\n");
}
}
return newNode;
}
EDIT #2: Code typo
Thanks for any help in advance. From what I have concluded my problem is that I am not moving through the list properly but I am unsure as to why I am not.
In your code, you have the line
newNode->next;
in your for loop. That operation doesn't do anything.
You also have
newNode-> = NULL;
which is not valid C, and I have no idea how you got that to compile.
But really, don't use that loop. A linked list is one of the most basic recursive data structures. As a result, almost all algorithms manipulating them are most elegant as a recursive solution.
typedef struct node node_t;
node_t* delete_at_index(node_t* head, unsigned i)
{
node_t* next;
if(head == NULL)
return head;
next = head->next;
return i == 0
? (free(head), next) /* If i == 0, the first element needs to die. Do it. */
: (head->next = delete_at_index(next, i - 1), head); /* If it isn't the first element, we recursively check the rest. */
}
Removing a given node n from a singly-linked list can be boiled down to this operation:
Set the pointer that points to n to point instead to n->next.
You can break this down into two operations:
Find the pointer that points to n;
Set that pointer to n->next.
The complication arises because the pointer that points to n might either be the p->next field of the previous node in the list, or the head pointer (if n is the first node in the list).
Your code does not appear to be complete - it doesn't ever set the ->next field of any node to anything, so it's hard to say what's actually wrong.
// Remove list's node located at specified position.
// Arguments:
// head -- list's head
// pos -- index of a node to be removed (1-based!!!)
struct node* DeleteNode(struct node* head, int pos)
{
struct node* node;
struct node* prev;
int length;
int i;
printf("DeleteNode: position = %d \nBefore: ", pos);
PrintList(head);
// Check position's lower bound. Should be >= 1
if(pos <= 0) { //node does NOT exist
printf("ERROR: Node does not exist!\n");
return head;
}
// Seek to the specified node, and keep track of previous node.
// We need previous node to remove specified node from the list.
for(i=1, prev = 0, node = head; i < pos && node != 0; i++) {
prev = node;
node = node->next;
}
// Out of range
if(0 == node) {
printf("ERROR: Index out of bounds!\n");
return head;
}
// #node points to a list's node located at index pos
// #prev points to a previous node.
// Remove current node from the list.
if(0 == prev) {
head = node->next;
}
else {
prev->next = node->next;
}
free(node);
return head;
}
Your DeleteNode doesn't delete a node, it removes pos nodes from the front of the list. So you're trying to remove 9 items from a list that only contains 6, resulting of course in an empty list (NULL). Also, your code is overly complex and contains remnants of previous attempts. Please don't do that to yourself or to us; provide simple clean code and it will be easier to understand and to fix.
Figured out your for loop isn't reaching the desired position you wanted.
Better use equal to sign for the constraint it will work.
e.g.
for (i=1;i<=position-1;i++)
{
}

Resources