王道oj/problem17


網址:http:oj.lgwenda.com/problem17

思路:指針其實就是存儲地址的一個空間,LinkList=LNode*

代碼:

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

typedef int ElemType;
typedef struct LNode {
ElemType data;
struct LNode* next;//指向下一個結點
} LNode,*LinkList;
//頭插法新建鏈表
LinkList CreatList1(LinkList& L)//list_head_insert
{
LinkList s; int x;
L = (LinkList)malloc(sizeof(LNode));//帶頭結點的鏈表,指針就是存地址的一個空間
L->next = NULL;
scanf("%d", &x);
while (x!= 9999) {
s = (LinkList)malloc(sizeof(LNode));//申請一個新空間s,強制類型轉換
s->data = x;//把讀到的值,給新空間中的data
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
return L;
}
//尾插法
LinkList CreatList2(LinkList& L)//list_tail_insert
{
int x;
L = (LinkList)malloc(sizeof(LNode));
LNode* s, * r = L;//LinkList s,r = L;也可以
//s代表新結點,r代表表尾結點
scanf("%d", &x);
while (x!= 9999)
{
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d", &x);
}
r->next = NULL;
return L;
}

void PrintList(LinkList L)//打印鏈表
{
L = L->next;
while (L != NULL)
{
printf("%d", L->data);
L = L->next;
if(L!=NULL)
printf(" ");
}
printf("\n");
}

int main()
{
LinkList L;//鏈表頭,是結構體指針類型
CreatList1(L);//輸入數據可以為3 4 5 6 9999
PrintList(L);
CreatList2(L);
PrintList(L);
return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM