Initialize linked list with array

 
  
#include<stdio.h> #include<stdlib.h> typedef struct Node{ int data; struct Node *next; }Node; Node *head(int a[]){//Turn the array into a linked list and return the linked list Head pointer Node *L,*current,*p; int i=0; L = (Node*)malloc(sizeof(Node)); current = L; L->next = NULL; while(a[i]!= '\0'){ p = (Node*)malloc(sizeof(Node)); p->data = a[i]; current->next = p; current = p; ++i; } current->next = NULL; return L; } int main(void){
        //Not much to say, verify this method int x[1024]={1,2,3,9,9,6};//Just make an array Node *L,*p; L = head(x) ;//Turn the array into a linked list and return the head pointer of the linked list p = L->next;//Start printing from the information of the starting node while(p!=NULL){ printf("%d\n",p- >data); p = p->next; } return 0; }
The effect is as shown in the figure


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326041758&siteId=291194637