Проблема перестановки элементов LinkedList в C - PullRequest
0 голосов
/ 31 марта 2011

Я написал программу, которая имеет много функций, но я не могу поменять 2 элемента из 2 узлов в связанном списке. На самом деле я могу поменять 2 узла, изменив их ссылки, но я не могу поменять 2 элемента, когда пользователь запросил замену 2 элементовВот мой код без какой-либо операции подкачки. Снова я должен сказать, что хочу сделать эту операцию подкачки, меняя 2 элемента узла, не меняя ссылки на узлы. Как я могу избавиться от этой проблемы? Любая помощь будет оценена.

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

struct node{
  int data;
  struct node *next;
     };
typedef struct node nodetype;

void insert(int ,struct node **);
void display(struct node *);
void search(int, struct node *);
void delete(int, struct node **);
int main(void){

    nodetype *p;
    p=NULL;
    int x=0,choice;
    int s_no,k,r_no;


    while(x!=1){
        printf("enter 1 for insert\n");
        printf("enter 2 for display\n");
        printf("enter 3 for search\n");
        printf("enter 4 for delete\n");

        printf("enter 0 for exit\n");
        fflush(stdout);
        scanf("%d",&choice);
        if(choice==1){
            printf("enter inserted  no\n");
            fflush(stdout);
             scanf("%d",&k);
            insert(k,&p);
        }

        else if(choice==2)
            display(p);
        else if(choice==3){
            printf("enter searched no\n");
            scanf("%d",&s_no);
            search(s_no, p);
        }
        else if(choice==4){
            printf("enter deleted no\n");
            scanf("%d",&r_no);
            delete(r_no,&p);
                }
        else
            printf("invalid choice\n");
    }
    return 0;
}
void display ( struct node *p)
{
    printf("the content is:\n");
    if(p==NULL)
        printf("the link is empty\n");
    while ( p != NULL )
    {
        printf ( "%d ", p -> data ) ;
        p = p -> next ;
    }
 printf ( "\n" ) ;
}

void search(int no, struct node *p){
   nodetype * loc;
   for(loc=p;loc!=NULL;loc=loc->next)
    {
     if(no==loc->data){
       printf("\nthe number exist in the list\n");
       return;
     }

    }
   printf("\nthe number is not exist in the \n");
 }
void insert(int x,struct node **p)
{
    struct node *r,*temp=*p;
    r = (struct node *)malloc ( sizeof (struct node)) ;
    r ->data = x ;
    r->next=NULL;
    if ( *p == NULL)
    {
        *p = r ;
    }
    else
    {
        while(temp->next!= NULL)
        {
                  temp=temp->next;
        }

     temp->next=r;
    }
}
void delete(int num, struct node **p){
  struct node *temp,*x;
  temp=*p;
  x= NULL;
  while (temp->next !=NULL){
    if(temp->data == num)
     {
      if (x==NULL)
       {
        *p = temp->next;
        free(temp);
        return;
       }
      else
       {
        x->next = temp->next;
        free(temp);
        return;
       }
     }
    x=temp;
    temp=temp->next;
  }
  printf(" No such entry to delete ");
}

1 Ответ

1 голос
/ 01 апреля 2011

Я попытался выполнить операцию свопинга с использованием введенных пользователем номеров. Например, пользователь ввел 12 и 45 для обмена в связанном списке. Как я могу это сделать?Предлагаем дополнить существующую функцию возвращаемыми значениями (не проверено только идея)

nodetype * search(int no, struct node *p){
   nodetype * loc;
   for(loc=p;loc!=NULL;loc=loc->next)
    {
     if(no==loc->data){
       printf("\nthe number exist in the list\n");
       return loc;
     }

    }
   printf("\nthe number is not exist in the \n");
   return NULL;
 }

После этого вы вызываете поиск обоих значений, введенных пользователем.Затем вы меняете значения на месте, не меняя никаких указателей, просто назначая новые значения.Конечно, вам нужно проверить, были ли фактически найдены узлы (не NULL).

nodetype *node1;
nodetype *node2;

node1 = search( userInput1, &p );
node2 = search( userInput2, &p );

int tmp_data = node1->data;
node1->data = node2->data;
node2->data = tmp;
...