Untitled

 avatar
unknown
plain_text
2 months ago
2.7 kB
3
Indexable
#include <stdio.h>
#include <stdlib.h>
struct node{
	int data;
	struct node *link;
};

struct node *head;
struct node *temp;

struct node *head = NULL;

struct node *create(struct node **head){ 
    struct node *temp;
	struct node *new;
	int data;
	    printf("Enter data (-1 to stop):\n ");
        scanf("%d", &data);
    
    while (data != -1) { 
        new = (struct node*)malloc(sizeof(struct node));
        if (new == NULL) {
            printf("Memory allocation failed!\n");
            return head;
        }
        new->data = data;
        new->link = NULL;

        if (head == NULL) {  
            head = new;  // First node
            temp = *head;
        } else {
            temp->link = new;
            temp = new;
        }

        printf("Enter data (-1 to stop):\n ");
        scanf("%d", &data);
    }
    return *head;
}
    void display(struct node *head){
        struct node *temp;
        temp = head;
        if(temp == NULL){
        	printf("No list Found!");
		}	
		else{
			while(temp->link != NULL){
			printf("%d->", temp->data);
			temp = temp->link;
		}
		temp->link = NULL;
    }
}
 struct node *reversedList(struct node **head){
   	struct node *temp;
	 struct node   *prev = NULL;
	 struct node  *link = NULL;
   	temp = *head;
   	while(temp != NULL){
   		link = temp->link;
   		temp->link=prev;
   		prev = temp;
   		temp = link;
   		
	   }
	   return prev;
   }
    int isPalindrome(struct node **head){
  	struct node *slow = *head, *temp = *head;
  	while(temp && temp->link){
  		slow= slow->link;
  		temp = temp->link->link;
	  }
	  struct node *revHead = reversedList(slow);
	  struct node *temp1 = *head;
	  struct node *temp2 = revHead;
	  while(temp2->link != NULL){
	  if (temp1->data == temp2->data){
        temp1 = temp1->link;
        temp2 = temp2->link;
    }
    else{
    	printf("Not a Palindrome..!");
	}
    return 1;
  }
}
   
   int main(){
    	int ch; 
    	printf("Enter choice:\n ");
    	do{
    		printf("1.create:\n");
            printf("2.display:\n");           
		    printf("3.reversedList:\n");
		    printf("4.isPalindrome:\n");
			printf("0.exit:\n");
			scanf("%d", &ch);
		switch(ch)
	{
		case 1:
		   head = create(&head);
	       break;
		case 2:
		  display(&head);
		  break;
		case 4:
            isPalindrome(&head);
            break;
		case 3:
			head = reversedList(&head);
			break;
		case 0:
	      printf("Exiting...\n");
	   	  break;
	    Default:
		  Printf("Invalid option:");	
		  break;	
		}
	}	while(ch!=0);
return 0;
}

Editor is loading...
Leave a Comment