reversing A Linked List:: Homework 3 Name: Buya MD Habib Hasan Shakil ID: 201932130119

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Homework 3

Name: Buya Md Habib Hasan Shakil


ID: 201932130119

//Reversing a linked list:

#include<stdio.h>
#include<stdlib.h>

/* Link list node */


struct Node
{
int data;
struct Node* next;
};

/* Function to reverse the linked list */


static void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}

/* Function to push a node */


void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));

/* put in the data */


new_node->data = new_data;

/* link the old list off the new node */


new_node->next = (*head_ref);

/* move the head to point to the new node */


(*head_ref) = new_node;
}

/* Function to print linked list */


void printList(struct Node *head)
{
struct Node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}

/* Driver program to test above function*/


int main()
{
/* Start with the empty list */
struct Node* head = NULL;

int n, temp;

scanf("%d", &n);

for(int i=0; i<n; i++){


scanf("%d", &temp);
push(&head, temp);
}

printList(head);
reverse(&head);
getchar();
}

for better view of code: https://paste.ubuntu.com/p/RpyjXQ79xJ/

You might also like