Created
April 26, 2017 09:31
-
-
Save thinkphp/f1db81211432b4433eefc2642c2b9f52 to your computer and use it in GitHub Desktop.
Doubly Linked List using **head pointer to pointer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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