I am trying to extract the head from a linked list (and also the tail, but that part works) with the following function:
Code:
void Remove (myllist *list){ //remove the head and return the removed node and the rest of the list
myllist * head, * tail;
int i;
//get the head
head = list;
head->link = NULL;
//check list
printf("\nPrinting list\n");
printList(list);
//print the results
printf("\nRemoved Node:\n");
printList(head);
//get the tail
tail = list->link;
//check list
printf("\nPrinting list\n");
printList(list);
//print the results
printf("\nTail of list:\n");
printList(tail);
printf("\nReturning to main.");
return;
}
myllist is:
Code:
typedef struct myllist
{
int info;
struct myllist * link;
} myllist;
The problem is that when I remove the tail from the list to get the head I am accidentally modifying the original list. I think this line is just creating a new pointer to the same information instead of copying the information into a new list:
How can I change it so that I can modify head without changing list?
Thanks!
The entire program is below if you need it.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct myllist
{
int info;
struct myllist * link;
} myllist;
void GetNewNode (int newInfo, myllist * pNode);
void disposeOfNode(myllist *change, myllist *remove);
void Remove (myllist *list);
void printList (myllist *list);
main(){
//setup nodes
myllist * pNode;
pNode = (myllist *) malloc(sizeof(*pNode));
GetNewNode(4, pNode);
myllist * pNode2;
pNode2 = (myllist *) malloc(sizeof(*pNode));
GetNewNode(5, pNode2);
myllist * pNode3;
pNode3 = (myllist *) malloc(sizeof(*pNode));
GetNewNode(6, pNode3);
//link nodes together
pNode->link = pNode2;
pNode2->link = pNode3;
//print list
printf("Old List:\n");
myllist * tmp;
tmp = pNode;
while(tmp->link != NULL){
printf("%d", tmp->info);
tmp = tmp->link;
}
printf("%d", tmp->info);
//do stuff to list
Remove(pNode);
//print new list
printf("\nNew List:\n");
printList(pNode);
//end
getchar();
}
void disposeOfNode(myllist *change, myllist *remove){
change->link = remove->link;
free(remove);
return;
}
void GetNewNode (int newInfo, myllist * pNode){
/*myllist * pNode;
pNode = (myllist *) malloc(sizeof(*pNode));*/
if(pNode == NULL){
printf("error: malloc failed");
}else{
pNode->info = newInfo;
pNode->link = NULL;
}
return;
}
void printList (myllist *list){
myllist * tmp;
tmp = list;
while(tmp != NULL){
printf("%d", tmp->info);
tmp = tmp->link;
}
}
void Remove (myllist *list){ //remove the head and return the removed node and the rest of the list
myllist * head, * tail;
int i;
//get the head
head = list;
head->link = NULL;
//check list
printf("\nPrinting list\n");
printList(list);
//print the results
printf("\nRemoved Node:\n");
printList(head);
//get the tail
tail = list->link;
//check list
printf("\nPrinting list\n");
printList(list);
//print the results
printf("\nTail of list:\n");
printList(tail);
printf("\nReturning to main.");
return;
}