C语言——单链表的建立

17

单链表的创建两种方法:头插法、尾插法。

单链表的输出。

#include <stdio.h>
#include <malloc.h>
typedef struct Node {
    int data;
    struct Node *next;
}LNode,*LinkList;
 // 创建单循环链表 ——尾插法
void CreateList(LNode *A) {
    LNode *p;
    int i,n;
    printf("输入要输入的个数:");
    scanf("%d",&n);
    printf("输入数据:");
    for(i = 0; i < n; i++) {
        p = (LNode *)malloc(sizeof(LNode));
        scanf("%d",&p->data);
       p->next=A->next;
       A->next = p;
       A = p;
    }
}
 // 创建单循环链表 ——头插法(输出的顺序与输入的顺序相反)
 /*void CreateList(LNode *A) {
    LNode *p;
    int i,n;
    printf("输入要输入的个数:");
    scanf("%d",&n);
    printf("输入数据:");
    for(i = 0; i < n; i++) {
        p = (LNode *)malloc(sizeof(LNode));
        scanf("%d",&p->data);
        p->next = A->next;
        A->next = p;
    }
}*/
//输出单链表
void PrintList(LNode *head) {
    LNode *p = head->next;
    while(p) {
        printf("%d ",p->data);
        p = p->next;
    }
}
//查询第i个位置的数据
void GetElem(LinkList L,int i){
    int j=1;
    LNode *p=L->next;
    if(i==0){
        return L;
    }
    if(i<1){
        return NULL;
    }
    while(p&&j<i){
        p=p->next;
        j++;
    }
    printf("%d",p->data);
}
int main() {
    LNode *A;
    A= (LNode *)malloc(sizeof(LNode));
    A->next=NULL;
    CreateList(A);//创建
//  GetElem(A,2);//查询第i个位置的数据
    PrintList(A);//输出数据
    return 0;
}