Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct _Node{
- int value;
- struct _Node *next;
- } Node;
- void printList(Node *head){
- if(head==NULL) return;
- printf("%d\n", head->value);
- printList(head->next);
- }
- int search(Node *head, int query){
- int res = 0;
- while(head!=NULL){
- if(head->value == query) return res;
- head = head->next;
- res++;
- }
- return (-1);
- }
- void moveFront(Node *head, int query){
- Node *curr = head;
- Node *prev = NULL;
- int found=0;
- while(!found){
- if(curr->value == query){
- found=1;
- }
- else{
- prev = curr;
- curr = curr->next;
- }
- }
- if(prev!=NULL){
- printf("***Not first element***\n");
- prev->next = curr->next;
- curr->next = head->next;
- head = curr;
- }
- }
- int main(){
- Node *head = malloc(sizeof(Node));
- Node *last = head;
- int n;
- scanf("%d", &n);
- int i, input;
- for(i=0; i<n; i++){
- scanf("%d", &input);
- Node *new = malloc(sizeof(Node));
- new->value = input;
- new->next = NULL;
- if(i==0){
- head = new;
- last = new;
- }
- else{
- last->next = new;
- last = new;
- }
- }
- printf("***Print List***\n");
- printList(head);
- printf("***Query Section***\n");
- int flag=1, query, position;
- while(flag){
- scanf("%d", &query);
- position = search(head, query);
- if(position>=0){
- printf("%d\n", position);
- moveFront(head, query);
- printf("***Print List***\n");
- printList(head);
- }
- else{
- flag = 0;
- printf("-1\n");
- }
- }
- printf("***Program Ended***\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement