1.建单向链表
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}Node;
// 请在此添加你的代码
/********** Begin **********/
Node *CreatList(void)
{
int val, i, n;
Node *phead, *p, *q;
phead = (Node *)malloc(sizeof(Node));
q=phead;
q->next=NULL;
scanf("%d", &n);
for(i=0; i<n; ++i)
{
scanf("%d", &val);
p = (Node *)malloc(sizeof(Node));
p->data=val;
q->next=p;
p->next=NULL;
q=p;
}
return phead;
}
void ShowList(Node *phead)
{
Node *p;
p = phead->next;
while(p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
/********** End **********/
int main(void)
{
Node *phead;
phead = CreatList();
ShowList(phead);
return 0;
}
2.统计单链表中的节点数
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}Node;
//请在此添加你的代码
/********** Begin *********/
Node *CreatList(void)
{
int val, i, n;
Node *phead, *p, *q;
phead = (Node *)malloc(sizeof(Node));
q=phead;
q->next=NULL;
scanf("%d", &n);
for(i=0; i<n; ++i)
{
scanf("%d", &val);
p = (Node *)malloc(sizeof(Node));
p->data=val;
q->next=p;
p->next=NULL;
q=p;
}
return phead;
}
void ShowList(Node *phead)
{
Node *p;
p = phead->next;
while(p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int Length(Node * phead)
{
int i=0;
struct node * pMove = phead->next;
while(pMove)
{
i++;
pMove=pMove->next;
}
return i;
}
/********** End **********/
int main(void)
{
Node *phead;
phead = CreatList();
ShowList(phead);
printf("%d", Length(phead));
return 0;
}
3.单链表逆置
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}Node;
// 请在此添加你的代码
/********** Begin *********/
Node *CreatList(void)
{
int val, i, n;
Node *phead, *p, *q;
phead = NULL;
scanf("%d", &n);
for(i=0; i<n; ++i)
{
scanf("%d", &val);
p = (Node *)malloc(sizeof(Node));
p->data = val;
if(NULL == phead)
q = phead = p;
else
q->next = p;
q = p;
}
p->next = NULL;
return phead;
}
Node *ReverseList(Node *phead)
{
Node *p, *q, *r;
p = phead;
q=r=NULL;
while(p)
{
q = p->next;
p->next = r;
r = p;
p = q;
}
return r;
}
void ShowList(Node *phead)
{
Node *p;
p = phead;
while(p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
/********** End **********/
int main(void)
{
Node *phead;
phead = CreatList();
printf("链表逆置前的数据:\n");
ShowList(phead);
phead = ReverseList(phead);
printf("链表逆置后的数据:\n");
ShowList(phead);
return 0;
}