I was having some problem when trying to do a double deferencing when inserting node into ListNode
. Here is the code:
#include "stdafx.h"
#include <stdlib.h>
typedef struct _listnode {
int num;
struct _listnode *next;
}ListNode;
void insertNode(ListNode **ptrHead, int index, int value);
ListNode *findNode(ListNode *head, int index);
int main()
{
int index, value, i;
ListNode **ptrHead, *head = NULL;
ptrHead = &head;
for (i = 0; i < 5; i++){
printf("Enter value: ");
scanf("%d", &value);
printf("Enter index: ");
scanf("%d", &index);
insertNode(ptrHead, index, value);
}
ptrHead = head;
while (ptrHead != NULL) {
printf("%d", head->num);
ptrHead = head->next;
}
return 0;
}
void insertNode(ListNode **ptrHead, int index, int value) {
ListNode *cur, *newNode;
if (*ptrHead == NULL || index == 0) {
newNode = malloc(sizeof(ListNode));
newNode->num = value;
newNode->next = *ptrHead;
*ptrHead = newNode;
}
else if ((cur = findNode(*ptrHead, index - 1)) != NULL) {
newNode = malloc(sizeof(ListNode));
newNode->num = value;
newNode->next = cur->next;
cur->next = newNode;
}
else printf("Cannot insert the new item at index %d!\n", index);
}
ListNode *findNode(ListNode *head, int index) {
ListNode *cur = head;
if (head == NULL || index < 0)
return NULL;
while (index > 0) {
cur = cur->next;
if (cur == NULL) return NULL;
index--;
}
return cur;
}
So basically I am taking 5 value and index inputs from the user. Then from there, I am inserting them into the ListNode
. Inside insertNode()
, there is a function called findNode
which trying to find the cur so that I can point my cur
to the next newNode
.
However, with these code, when I try to print out the ListNode
, it printed out the first value input infinitely. So I was thinking which part was my mistakes?
Thanks in advance.
In your main
function, the following lines of code:
ptrHead = head;
while (ptrHead != NULL) {
printf("%d", head->num);
ptrHead = head->next;
}
shall be:
ListNode *cur = head;
while (cur != NULL) {
printf("%d", cur->num);
cur = cur->next;
}
EDITED:
But can I know why it does not work when I assign head to ptrHead. Is it because I am double deferencing the ptrHead?
They are of different types. ptrHead
is ListNode**
while head
is ListNode*
. Thus the assignment ptrHead = head;
shall not do what you really want. Also a modern compiler shall have raised some warning on this line.