Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created April 26, 2017 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkphp/f1db81211432b4433eefc2642c2b9f52 to your computer and use it in GitHub Desktop.
Save thinkphp/f1db81211432b4433eefc2642c2b9f52 to your computer and use it in GitHub Desktop.
Doubly Linked List using **head pointer to pointer
#include <stdio.h>
#include <malloc.h>
typedef struct node {
int data;
struct node* next,
* prev;
} Node;
void push(Node**head, int data) {
//dynamic allocation for a new node
Node *temp = (Node*)malloc(sizeof(Node));
//put in data
temp->data = data;
//update next area
temp->next = (*head);
//update prev area
temp->prev = NULL;
if((*head) != NULL) (*head)->prev = temp;
//move the head here
(*head) = temp;
};
void print(Node *head) {
while(head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
void printR(Node *head) {
Node*last;
while(head != NULL) {
last = head;
head = head->next;
}
while(last != NULL) {
printf("%d ",last->data);
last = last->prev;
}
}
int main() {
Node *head = NULL;
push(&head,1);
push(&head,2);
push(&head,3);
push(&head,4);
push(&head,5);
push(&head,6);
push(&head,7);
print(head);
printR(head);
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment