Intro to C
  • Introduction to Programming in C
  • Session 1
    • session1.c
  • Session 2
    • session2.c
  • Session 3
    • session3.c
    • veggies.c
  • Session 4
    • session4.c
  • Session 5
    • session5.c
    • session5p.c
  • Session 6
    • session6.c
    • session6p.c
  • Session 7
    • session7.c
    • session7p.c
    • tictactoe.c
  • Session 8
    • session8.c
    • session8p.c
  • Session 9
    • session9.c
    • session9p.c
    • data3.txt
    • problem4.txt
    • problem5.txt
    • problem6.txt
    • hello.txt
    • sentences.txt
    • people.csv
    • students.csv
    • powerball.csv
  • Session 10
    • session10.c
    • Linked List Code
    • Double Linked List Code
Powered by GitBook
On this page
  1. Session 10

Double Linked List Code

struct DoubleNode {
    int data;
    struct DoubleNode* prev;
    struct DoubleNode* next;
};

// Function to create a new double node
struct DoubleNode* createDoubleNode(int data) {
    struct DoubleNode* newNode = (struct DoubleNode*)malloc(sizeof(struct DoubleNode));
    if (newNode != NULL) {
        newNode->data = data;
        newNode->prev = NULL;
        newNode->next = NULL;
    }
    return newNode;
}

// Function to insert a new double node at the beginning of the list
void insertDoubleAtBeginning(struct DoubleNode** head, int data) {
    struct DoubleNode* newNode = createDoubleNode(data);
    if (newNode != NULL) {
        if (*head != NULL) {
            (*head)->prev = newNode;
            newNode->next = *head;
        }
        *head = newNode;
    }
}

// Function to insert a new double node at the end of the list
void insertDoubleAtEnd(struct DoubleNode** head, int data) {
    struct DoubleNode* newNode = createDoubleNode(data);
    if (newNode != NULL) {
        if (*head == NULL) {
            *head = newNode;
        } else {
            struct DoubleNode* temp = *head;
            while (temp->next != NULL) {
                temp = temp->next;
            }
            temp->next = newNode;
            newNode->prev = temp;
        }
    }
}

// Function to display the elements of the double linked list
void displayDoubleList(struct DoubleNode* head) {
    printf("Doubly Linked List: ");
    struct DoubleNode* temp = head;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

// Function to free the memory used by the double linked list
void freeDoubleList(struct DoubleNode* head) {
    struct DoubleNode* temp;
    while (head != NULL) {
        temp = head;
        head = head->next;
        free(temp);
    }
}
PreviousLinked List Code

Last updated 1 year ago