Im trying to insert a node at the head of a linked list, and I'm not exactly sure why this function isn't working. I thought it was a fairly simple task, but I seem to be missing something here. I've also included my structs and a portion of main so you can get a clearer understanding of the code. Thanks
typedef struct node
{
struct node *next;
int data;
} node;
typedef struct LinkedList
{
node *head;
node *tail;
} LinkedList;
LinkedList *create_list(void)
{
return calloc(1, sizeof(LinkedList));
}
node *create_node(int data)
{
node *ptr = calloc(1, sizeof(node));
ptr->data = data;
return ptr;
}
void head_insert(LinkedList *list, int data) // problem
{
node *newHead = create_node(data);
newHead->next = list->head;
}
void print_list_helper(node *head)
{
if (head == NULL)
return;
printf("%d%c", head->data, (head->next == NULL) ? '\n' : ' ');
print_list_helper(head->next);
}
void print_list(LinkedList *list)
{
if (list == NULL || list->head == NULL)
return;
print_list_helper(list->head);
}
int main(void)
{
LinkedList *list = create_list();
head_insert(list, 8);
print_list(list); // print linked list function
return 0;
}
So I created a new Node, and set node->next to the head of the list. Im not sure what else im missing here. I have another function that prints the lists, thats why the function is void.
Add these lines at the end of your head_insert() function definition:
if (list->head == NULL)
{
list->tail = newHead;
}
list->head = newHead;
In your function, after adding new node at head the struct LinkedList still pointed to the previous head. You should change that head to the newly inserted head. And if there was no nodes in the list you should also set the newly created head
Here is the full function.
void head_insert(LinkedList *list, int data)
{
node *newHead = create_node(data);
newHead->next = list->head;
if (list->head == NULL)
{
list->tail = newHead;
}
list->head = newHead;
}
Related
I am trying to implement a doubly linked list in order to study for an exam and am running into some trouble when inserting items into the tail -- it prints out correctly when I only insert to the head in the list. However, when I insert to the tail in the list only the last tail item is printed out. Below is my full code:
/*
- Q2: Write a function that takes a LinkedList struct pointer and inserts at the head of the linked list.
- Q3. Write a function that takes a LinkedList struct pointer and frees all memory associated with it. (
For a solution, see fancy-linked-lists.c, attached above.)
- Q4 Review all the functions from today's code and give their big-oh runtimes.
- Q5: Implement functions for doubly linked lists:
- tail_insert(),
- head_insert(),
- tail_delete(),
- head_delete(),
- delete_Nth().
- Repeat these exercises with doubly linked lists in which you maintain a tail pointer.
- How does the tail pointer affect the runtimes of these functions?
- Are any of these functions more efficient for doubly linked lists with tail pointers than they are for singly linked lists with tail pointers?
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
struct node *prev;
} node;
node *createNode(int data)
{
node *ptr = NULL;
ptr = malloc(sizeof(node));
if(ptr == NULL)
{
printf("space could not be allocated\n");
return NULL;
}
ptr->data = data;
ptr->next = NULL;
ptr->prev = NULL;
return ptr;
}
node *tailInsert(node *head, int data)
{
if(head->next == NULL)
{
node *temp;
temp = createNode(data);
temp->next = NULL;
temp->prev = head;
head->next = temp;
return head;
}
tailInsert(head->next, data);
}
node *frontInsert(node *head, int data)
{
node *newHead;
if(head == NULL)
{
return createNode(data);
}
newHead = createNode(data);
newHead->next = head;
newHead->prev = NULL;
return newHead;
}
node *destroy_linked_list(node *list)
{
/*if (list == NULL)
return NULL;
// Free the entire list within this struct.
destroy_list(list->head);
// Free the struct itself.
free(list);
return NULL;
*/
}
void printList(node *head)
{
if (head == NULL)
{
printf("Empty List\n");
return;
}
for(; head != NULL; head = head->next)
printf("%d ", head->data);
printf("\n");
}
int main(void)
{
node *head = NULL;
head = frontInsert(head, 1);
head = frontInsert(head, 2);
head = frontInsert(head, 3);
head = tailInsert(head, 4);
head = tailInsert(head, 5);
head = tailInsert(head, 6);
printList(head);
system("PAUSE");
return 0;
}
I appreciate the help!
You are returning the temp(last node) from tailInsert and assigning to head. Do not change the head pointer if you are inserting at tail.
void tailInsert(node *head, int data)
{
if(head->next == NULL)
{
node *temp;
temp = createNode(data);
temp->next = NULL;
temp->prev = head;
head->next = temp;
return ;
}
tailInsert(head->next, data);
}
In main do not assign anything to head if you are calling tailInsert function
I am having a tough time deleting all members in a linked in a single function. If I break it up like you see below, it works fine, but this seems wildly inefficient and want to figure out the correct way to do this. in order to free all nodes I need to have function to first free all nodes other then the head, then have a function free the head link. this seems like it would be easy to do but I am having trouble.
Thanks for the help!
int main() {
struct node *head = NULL;
createList(&head);
//do stuff with list
freeListMembers(head);
freeListHead(&head);
return 0;
}
int createList(struct node **head) {
//create list
return 0;
}
void freeListMembers(struct node *head){
while(head->next != NULL){
head->next = NULL;
free(head->next);
}
return;
}
void freeListHead(struct node **head) {
*head = NULL;
free(*head);
return;
}
here is the code that I want to work but does not. the issue I am seeing is a an error for "*head->next;" where it sais "expression must have pointer to struct or union type"
int main() {
struct node *head = NULL;
createList(&head);
//do stuff with list
freeAllListMembers(&head);
return 0;
}
int createList(struct node **head) {
//create list
return 0;
}
void freeAllListMembers(struct node **head){
while (head != NULL) {
struct node *temp = *head->next;
free(*head);
*head = temp ;
}
return;
}
From your code :
void freeListMembers(struct node *head){
while(head->next != NULL){
head->next = NULL;
free(head->next);
}
return;
}
This is freeing NULL, not your node*.
Freeing the list is as simple as using a temporary pointer to the next node.
while (head) {
node* next = head->next;
free(head);
head = next;
}
From your edit :
void freeAllListMembers(struct node **head){
while (head != NULL) {
struct node *temp = *head->next;
free(*head);
*head = temp ;
}
return;
}
There are a couple errors with this. It should be while (*head != NULL) and (*head)->next. The first is a logic error, because head will always be non-NULL, and the second is a syntax error, because you need to dereference the head pointer before accessing the next pointer.
This will work. You just set next of head to null and freed head. Now we can not move to second element.So we wont be able to free the nodes.Also check base condition. I hope it helps
void freeListmembers(node *head){
node *temp=head;
if(head==NULL)//Base condition
return;
while(head->next!=NULL){
temp=head;//Moved temp to head. we will move head to next and free the previous node
head=head->next;
free(temp);
}
free(head);
return;
}
Hi I wish to implement a simple linked list and all the values to the end of the list. As simple as that but I am not able to do so. Can you please tell me where I am doing it wrong ? Initially I am declaring a pointer and assigning NULL value to it. Later in each iteration I am allocating memory to the pointer that was initially NULL.
#include <stdio.h>
#include <malloc.h>
struct node{
int a;
struct node* next;
};
struct node* insert(struct node* start,int value);
void print(struct node* head);
int main()
{
int a;
struct node* head = NULL;
while(scanf("%d",&a) != EOF)//taking input
{
head = insert(head,a);
print(head);
}
return 0;
}
struct node* insert(struct node* start,int value)
{
struct node* head = start;
while(start != NULL)
{
start = start->next;//getting upto the end of the linked list
}
start = (struct node*)malloc(sizeof(struct node));//allocating memory at the end
start->a = value;
start->next = NULL;
if(head == NULL)
{
return start;//for the base case when list is initally empty
}
return head;
}
void print(struct node* head)
{
while(head != NULL)
{
printf("%d\n",head->a);
head = head->next;
}
return;
}
You're losing your linkage between your tail and your new node, try this instead
struct node* insert(struct node* head,int value)
{
struct node* tail = head;
while(tail != NULL && tail->next != NULL)
{
tail= tail->next;//getting upto the end of the linked list
}
struct node* start = (struct node*)malloc(sizeof(struct node));//allocating memory at the end
start->a = value;
start->next = NULL;
if(head == NULL)
{
return start;//for the base case when list is initally empty
}
else
{
tail->next = start;
}
return head;
}
struct node* insert(struct node* start,int value){
struct node* head = start;
struct node* np = (struct node*)malloc(sizeof(struct node));
np->a = value;
np->next = NULL;
if(head == NULL)
return np;
while(start->next != NULL){
start = start->next;
}
start->next = np;
return head;
}
What makes the approach I am using buggy ?
nodeX
|
+a
|
+next(address to OtherX)
nodeX.next = new_node;//update link(case of OK)
tempPointer = nodeX.next;//address to OtherX set to tempPointer
tempPointer = new_node;//contents of tempPointer changed, but orignal (nodeX.next not change)
This is my code. I made three functions for adding a new node, inserting a new node between two others, and one deleting, but I dont know how to delete the first node. I dont even have any idea.
#include <stdlib.h>
#include <stdio.h>
struct Node
{
int data;
struct Node *next;
};
void insert(Node* insertafter, Node* newNode);
void add(Node* llist,Node* newNode);
void deleteafter(Node *llist);
void deletefirts();
int main()
{
struct Node *llist;
struct Node *newNode;
newNode = (Node*)malloc(sizeof(struct Node));
newNode->data = 13;
struct Node *newNode2;
newNode2 = (Node*)malloc(sizeof(struct Node));
newNode2->data = 14;
llist = (Node*)malloc(sizeof(struct Node));
llist->data = 10;
llist->next = (Node*)malloc(sizeof(struct Node));
llist->next->data = 15;
llist->next->next = NULL;
insert(llist,newNode);
add(llist,newNode2);
if(llist->next == NULL)
printf("shecdoma");
struct Node *cursor = llist;
while (cursor != NULL)
{
printf("%d\n", cursor->data);
cursor = cursor->next;
}
system("pause");
return 0;
}
void insert(Node* insertafter, Node *newNode)
{
newNode->next = insertafter->next;
insertafter->next = newNode;
}
void add(Node* llist,Node *newNode)
{
if(llist->next == NULL)
{
llist->next = newNode;
newNode->next = NULL;
}
else
{
while(llist->next != NULL)
{
llist = llist->next;
}
add(llist,newNode);
}
void deleteafter(Node *llist)
{
if(llist->next != NUll)
llist->next = llist->next->next;
}
void deletefirst();
{
}
You can use something like:
void deletefirst (struct Node **head) {
struct Node *tmp = *head; // save old head for freeing.
if (tmp == NULL) return; // list empty? then do nothing.
*head = tmp->next; // advance head to second node.
free (tmp); // free old head.
}
You pass in the pointer to the head so that you can change it. Deleting nodes other than the first does not require this but deleting the first node does.
You set up a temporary pointer to the head so you free it, then you change the head to point to its next element. Then you free the old head and return.
void deleteFirst(Node** list)
{
Node* temp = *list;
if (*list != NULL)
{
*list = (*list)->next;
free(temp);
}
}
Going through classic data structures and have stopped on linked lists.Just implemented a circular singly-linked list, but I'm under overwhelming impression that this list could be expressed in a more elegant manner, remove_node function in particular.
Keeping in mind efficiency and code readability, could anybody present a more concise and efficient solution for singly-linked circular list?
#include <stdio.h>
#include <stdlib.h>
struct node{
struct node* next;
int value;
};
struct list{
struct node* head;
};
struct node* init_node(int value){
struct node* pnode;
if (!(pnode = (struct node*)malloc(sizeof(struct node)))){
return NULL;
}
else{
pnode->value = value;
}
return pnode;
}
struct list* init_list(){
struct list* plist;
if (!(plist = (struct list*)malloc(sizeof(struct list)))){
return NULL;
}
plist->head = NULL;
return plist;
}
void remove_node(struct list*a plist, int value){
struct node* current, *temp;
current = plist->head;
if (!(current)) return;
if ( current->value == value ){
if (current==current->next){
plist->head = NULL;
free(current);
}
else {
temp = current;
do {
current = current->next;
} while (current->next != plist->head);
current->next = plist->head->next;
plist->head = current->next;
free(temp);
}
}
else {
do {
if (current->next->value == value){
temp = current->next;
current->next = current->next->next;
free(temp);
}
current = current->next;
} while (current != plist->head);
}
}
void print_node(struct node* pnode){
printf("%d %p %p\n", pnode->value, pnode, pnode->next);
}
void print_list(struct list* plist){
struct node * current = plist->head;
if (!(current)) return;
if (current == plist->head->next){
print_node(current);
}
else{
do {
print_node(current);
current = current->next;
} while (current != plist->head);
}
}
void add_node(struct node* pnode,struct list* plist){
struct node* current;
struct node* temp;
if (plist->head == NULL){
plist->head = pnode;
plist->head->next = pnode;
}
else {
current = plist->head;
if (current == plist->head->next){
plist->head->next = pnode;
pnode->next = plist->head;
}
else {
while(current->next!=plist->head)
current = current->next;
current->next = pnode;
pnode->next = plist->head;
}
}
}
Take a look at the circular linked list in the Linux kernel source: http://lxr.linux.no/linux+v2.6.36/include/linux/list.h
Its beauty derives from the fact that you don't have a special struct for your data to fit in the list, you only have to include the struct list_head * in the struct you want to have as a list. The macros for accessing items in the list will handle the offset calculation to get from the struct list_head pointer to your data.
A more verbose explanation of the linked list used in the kernel can be found at kernelnewbies.org/FAQ/LinkedLists (Sorry, I dont have enough karma to post two hyperlinks).
Edit: Well, the list is a double-linked list and not a single-linked one like you have, but you could adopt the concept and create your own single-linked list.
List processing (particularly of circular lists) gets way easier when you treat the list head like an element of the list (a so-called "sentinel"). A lot of special cases just disappear. You can use a dummy node for the sentinel, but if the next pointer is first in the struct, you don't need to do even that. The other big trick is to keep a pointer to the next pointer of the previous node (so you can modify it later) whenever you modify the list. Putting it all together, you get this:
struct node* get_sentinel(struct list* plist)
{
// use &plist->head itself as sentinel!
// (works because struct node starts with the next pointer)
return (struct node*) &plist->head;
}
struct list* init_list(){
struct list* plist;
if (!(plist = (struct list*)malloc(sizeof(struct list)))){
return NULL;
}
plist->head = get_sentinel(plist);
return plist;
}
void add_node_at_front(struct node* pnode,struct list* plist){
pnode->next = plist->head;
plist->head = pnode;
}
void add_node_at_back(struct node* pnode,struct list* plist){
struct node *current, *sentinel = get_sentinel(plist);
// search for last element
current = plist->head;
while (current->next != sentinel)
current = current->next;
// insert node
pnode->next = sentinel;
current->next = pnode;
}
void remove_node(struct list* plist, int value){
struct node **prevnext, *sentinel = get_sentinel(plist);
prevnext = &plist->head; // ptr to next pointer of previous node
while (*prevnext != sentinel) {
struct node *current = *prevnext;
if (current->value == value) {
*prevnext = current->next; // remove current from list
free(current); // and free it
break; // we're done!
}
prevnext = ¤t->next;
}
}
void print_list(struct list* plist){
struct node *current, *sentinel = get_sentinel(plist);
for (current = plist->head; current != sentinel; current = current->next)
print_node(current);
}
A few comments:
I think the remove function doesn't correctly adjust the circular list pointers when you delete the head node and the list is larger than 3 elements. Since the list is circular you have to point the last node in the list to the new head.
You might be able to shorten the remove function slightly by creating a "find_node" function. Since the list is circular, however, there will still be the edge case of deleting the head node which will be more complex than in a non-circular list.
Code "beauty" is in the eye of the beholder. As code goes yours is easy to read and understand which beats a lot of code in the wild.
I use the following to create a dynamic circular singly linked list. All it requires is the size.
Node* createCircularLList(int size)
{
Node *it; // to iterate through the LList
Node *head;
// Create the head /1st Node of the list
head = it = (Node*)malloc(sizeof(Node));
head->id = 1;
// Create the remaining Nodes (from 2 to size)
int i;
for (i = 2; i <= size; ++i) {
it->next = (Node*)malloc(sizeof(Node)); // create next Node
it = it->next; // point to it
it->id = i; // assign its value / id
if (i == 2)
head->next = it; // head Node points to the 2nd Node
}
// close the llist by having the last Node point to the head Node
it->next = head;
return head; // return pointer to start of the list
}
And i define Node ADT like so:
typedef struct Node {
int id;
struct Node *next;
} Node;