Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- struct Node {
- int data;
- struct Node *next;
- struct Node *prev;
- };
- struct Node *head;
- struct Node* GetNewNode(int x){
- struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
- newNode->data=x;
- newNode->prev=NULL;
- newNode->next=NULL;
- return newNode;
- }
- void InsertAtHead(int x){
- struct Node *newNode = GetNewNode(x);
- if(head == NULL){
- head = newNode;
- return;
- }
- head->prev = newNode;
- newNode->next = head;
- head = newNode;
- }
- void insertAtTail(int x){
- struct Node* last = head;
- struct Node *newNode = GetNewNode(x);
- if(head == NULL){
- head = newNode;
- return;
- }
- newNode->next = NULL;
- while(last->next != NULL){
- last = last->next;
- }
- last->next=newNode;
- newNode->prev=last;
- }
- void insertAfter(int loc, int x){
- struct Node *temp=head;
- for(int i=0;i<loc;i++){
- temp = temp->next;
- }
- struct Node* prevNode = temp;
- struct Node *newNode = GetNewNode(x);
- newNode->next = prevNode->next;
- prevNode->next=newNode;
- newNode->prev=prevNode;
- if (newNode->next != NULL){
- newNode->next->prev = newNode;
- }
- printf("%d", *(newNode->prev));
- }
- void Print(){
- struct Node *temp = head;
- while(temp != NULL){
- printf("%d ", temp->data);
- temp = temp->next;
- }
- }
- void RevPrint(){
- struct Node *temp = head;
- while(temp->next != NULL){
- temp = temp->next;
- }
- while(temp != NULL){
- printf("%d ", temp->data);
- temp = temp->prev;
- }
- }
- int main()
- {
- head = NULL;
- InsertAtHead(2); Print(); RevPrint();
- printf("\n");
- InsertAtHead(4); Print(); RevPrint();
- printf("\n");
- InsertAtHead(6); Print(); RevPrint();
- printf("\n");
- insertAtTail(5); Print(); RevPrint();
- printf("\n");
- insertAfter(1, 55 ); Print(); RevPrint();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement