简体   繁体   English

将数组元素加入链表

[英]Adding elements of array into linked list

I have array elements ar1[i] i want to add the data of this array into linked list我有数组元素ar1[i]我想将此数组的数据添加到链表中

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


void create(struct node *head,int ar1[] int i1)
{
struct node *temp, *p, *q;
int i;


head = (struct node*)malloc(sizeof(struct node));
temp = (struct node*)malloc(sizeof(struct node));


for (i=0; i<i1; i++) //lets say i1 is no. of data in array
{
    if(head == NULL)
    {
        head->data = ar1[i];
        head->next = NULL;
    }
    else
    {
        temp->data = ar1[i];
        temp->next = NULL;

        p = head;
        while(p->next != NULL)
            p = p->next;
        p->next = temp;
    }

}

I did this program but its not working.我做了这个程序,但它不起作用。 It is accepting input data but not showing output and neither terminating the program.它接受输入数据,但不显示输出,也不终止程序。

Edit : As everyone suggested in comments I tried my best and came up with solution.编辑:正如每个人在评论中建议的那样,我尽我所能并提出了解决方案。 Actually my program was to get at most 10 digit number from user and perform Arithmetic operations on it.实际上我的程序是从用户那里获取最多 10 位数字并对其执行算术运算。

Here is my code :这是我的代码:

   /*
     WAP to store at most 10 digit integer in a Singly linked list and 
     perform
      arithmetic operations on it.
   */

   #include<iostream>
   using namespace std;

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

void create(struct node *head,int ar1[],int ar2[], int i1, int i2)
{
struct node *newNode, *temp;
int i=0;

head = (struct node *)malloc(sizeof(struct node));

if(head == NULL)
{
    cout<<"Unable to allocate memory.";
}
else
{

    head->data = ar1[i]; // Link the data field with data
    head->next = NULL; // Link the address field to NULL

    temp = head;

    for(i=1; i<i1; i++)     //Create n nodes and adds to linked list
    {
        newNode = (struct node *)malloc(sizeof(struct node));

        if(newNode == NULL)     

        {
            cout<<"Unable to allocate memory.";
            break;
        }
        else
        {


            newNode->data = ar1[i]; 
            newNode->next = NULL;

            temp->next = newNode; 
            temp = temp->next; 
        }
    }
}

temp = head;

while(temp!=NULL)
{
    cout<<temp->data<<" ";
    temp= temp->next;
}   

}

int main()
{
struct node*head = NULL ;
int n1,n2;
int i1,i2,choice;
int ar1[10],ar2[10];

head = (struct node*)malloc(sizeof(struct node));

cout<<"Enter numbers you want to perform operations on\n1). ";
cin>>n1;
cout<<"2). ";
cin>>n2;

i1=0; i2=0;

while(n1)       //getting each digit of given number
{

    ar1[i1] = n1 %10;
    n1 /= 10;
    i1= i1 + 1;     
}

while(n2)       //getting each digit of given number
{

    ar2[i2] = n2 % 10;
    n2 /= 10;
    i2++;   
}

cout<<"\nChoose what operation you want to 
 perform:\n1.Addition\n2Subtraction\n";
cin>>choice;

create(head,ar1,ar2,i1,i2);
/*if(choice == 1)  I comment out this part i.e. not important rn.
{
    add(ar1,ar2);
}
else if (choice == 2)
    sub();
else
{
    cout<<"Please chose valid data\n";
}
*/
return 0;
}

There are many issues.The whole logic of your create function is wrong:问题很多。你的create函数的整个逻辑是错误的:

void create(struct node *head, int ar1[], int i1)
{
  struct node *temp, *p, *q;
  int i;

  head = (struct node*)malloc(sizeof(struct node));  // Problem 1
  temp = (struct node*)malloc(sizeof(struct node));

  for (i = 0; i < i1; i++)
  {
    if (head == NULL)                                // Problem 2
    {
      head->data = ar1[i];  
      head->next = NULL;
    }
    else
    {
      temp->data = ar1[i];
      temp->next = NULL;

      p = head;
      while (p->next != NULL)
        p = p->next;

      p->next = temp;                                // Problem 3
    }
  }
}


...
create(myhead, myarray, maysize);                    // Problem 4
...

Problem 1问题一

You allocate memory too early, you should allocate it only whe you really need it.你分配内存过早,你应该只在你真正需要的时候分配它。

Problem 2问题二

Partly induced by Problem 1: head cannot be NULL here (assuming malloc doesn't fail, but that's another story) because you've assigned it to a non NULL value just before.部分由问题 1 引起:这里的head不能为NULL (假设malloc不会失败,但那是另一回事),因为您之前已将其分配给非NULL值。

Problem 3问题三

Here p->next is always NULL because of the while loop just above.由于上面的while循环,这里p->next始终为NULL

Problem 4问题四

Suppose you cann create likes this:假设你不能像这样create

...
myhead = NULL;
...
create(myhead, myarray, maysize);

myhead will still be NULL after the call to create , you should read this SO article .调用createmyhead仍然为NULL ,您应该阅读这篇 SO 文章

Just understand the logic by using paper and pencil , then sequentially optimize the code .用纸笔理解逻辑,然后依次优化代码。

struct node
{
    int val;
    struct node *next;
};
struct node *head=NULL, *last=NULL;

void insert( int value)
{
    struct node *tmp;
    tmp=(struct node *)malloc(sizeof(struct node));
    tmp->val=value;
    tmp->next=NULL;
    if( head == NULL )
    {
        head=tmp;
        last=tmp;
    }
    else
    {
        last->next=tmp;
        last=tmp;
    }
}

void printlist()
{
    struct node *tmp=head;
    printf("The list is:");
    while( tmp != NULL )
    {
        printf(" %d", tmp->val);
        tmp=tmp->next;
    }
    printf("\n");
}
void search( )
{
    printf("Which value to Search?");
    int n, k=0;
    scanf("%d",&n);
    struct node *tmp=head;
    while( tmp != NULL )
    {
        if( tmp->val == n )
            k=1;
        tmp=tmp->next;
    }
    if( k )
        printf("Yes\n");
    else
        printf("No\n");
}
void deletenode( )
{
    int n, posi;
    printf("Where to Delete?\n");
    printf("1\tFirst Position\n");
    printf("2\tLast Position\n");
    printf("3\tAny Desired Position\n");
    scanf("%d",&n);
    if( n == 1 )
    {
        struct node *tmp=head;
        tmp=tmp->next;
        head=tmp;
        printlist();
    }
    else if( n == 2 )
    {
        struct node *tmp=head ;
        while( 1 )
        {
            if( tmp->next->next == NULL )
            {
                tmp->next=NULL;
                break;
            }
            else
                tmp=tmp->next;
        }
        printlist();
    }
    else if( n == 3 )
    {
        int i=1;
        printf("Enter Position: ");
        scanf("%d",&posi);
        struct node *tmp=head;
        while( tmp->next != NULL && i <= posi )
        {
            if( i+1 == posi )
            {
                tmp->next=tmp->next->next;
                break;
            }
            else
            {
                i++;
                tmp=tmp->next;
            }
        }
        printlist();
    }
}

void ins()
{
    int n, v, posi;
    printf("Where to insert?\n");
    printf("1\tFirst Position\n");
    printf("2\tLast Position\n");
    printf("3\tAny Desired Position\n");
    scanf("%d",&n);
    if( n == 1 )
    {
        printf("Enter value: ");
        scanf("%d",&v);
        struct node *tmp;
        tmp=(struct node *)malloc( sizeof(struct node));
        tmp->val=v;
        tmp->next=head;
        head=tmp;
        printlist();
    }
    else if( n == 2 )
    {
        printf("Enter value: ");
        scanf("%d",&v);
        struct node *tmp;
        tmp=(struct node *)malloc(sizeof(struct node));
        tmp->val=v;
        tmp->next=NULL;
        last->next=tmp;
        last=tmp;
        printlist();
    }
    else if(n == 3 )
    {
        int i=1;
        printf("Enter position: ");
        scanf("%d",&posi);
        printf("\nEnter value: ");
        scanf("%d",&n);
        struct node *tmp1, *tmp=head, *tmp2;
        tmp1=(struct node *)malloc(sizeof(struct node));
        tmp1->val=n;
        tmp1->next=NULL;
        while( tmp->next != NULL && i <= posi)
        {
            if( i+1 == posi )
            {
                tmp2=tmp->next;
                tmp->next=tmp1;
                tmp1->next=tmp2;
            }
            i++;
            tmp=tmp->next;
        }
        printlist();
    }
}
int main()
{
    int n;
    printf("Enter value & Enter -1 to exit.\n");
    while( 1 )
    {
        scanf("%d",&n);
        if( n < 0 )
            break;
        insert(n);
    }
    printlist();
    printf("Enter choice:\n\n");
    printf("1\tInsert\n");
    printf("2\tDelete\n");
    printf("3\tSearch\n");
    printf("4\tExit\n");
    scanf("%d",&n);
    if( n == 1 )
        ins();
    else if( n == 2 )
        deletenode();
    else if( n == 3 )
        search();
    else if( n == 4 )
        return 0;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM