原来已经学习过,单链表比较简单,此处就不配图了
直接上代码:
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node * next;
}node,*nodeptr;
nodeptr creatlist()
{
nodeptr phead = (nodeptr)malloc(sizeof(node));
phead->next = NULL;
if (phead == NULL)
{
printf("fail to creat\n");
return NULL;
}
else
{
printf("creating success\n");
return phead;
}
}
//q1:第一次创建时会建立phead,而后建立新的节点则不需要建立Phead,如何实现
//a1:creatlist的功能只是建立phead,建立新的节点是add的功能
int length(nodeptr phead)
{
int length = 0; nodeptr p = phead;
while (p->next != NULL)
{
length++;
p = p->next;
}
return length;
}
void add(nodeptr phead,int data,int position)
{
nodeptr newnode = (nodeptr)malloc(sizeof(node));
newnode->data = data;
newnode->next = NULL;
//position是指添加完后,该数字的位置
int i = 0; nodeptr p = phead;
if (position > length(phead) + 1||position<=0)
{
printf("invalid input\n");
return;
}
for (i = 0; i < position - 1; i++)
{
p = p->next;
}
newnode->next = p->next;
p->next = newnode;
}
void print(nodeptr phead)
{
nodeptr p = phead->next;
if (length(phead) == 0)
{
printf("the list is empty\n");
return;
}
while (p != NULL)
{
printf("%d", p->data);
p = p->next;
}
printf("\n");
}
void deletenode(nodeptr phead,int position)
{
//position是要删除的数据的位置
if (position > length(phead)||position<=0)
{
printf("invalid input\n");
return;
}
//position > length(phead)||position<=0
//当length=0时,已经包含position所有情况
//empty属于特殊的invalid input
//经考虑,将empty情况放在print里更为合适
nodeptr p = phead; int i;
for(i=1;i<position;i++)
{
p = p->next;
}
//p是要被删除的前一个位置
nodeptr q = p->next;
p->next = p->next->next;//! ! !question:这里能不能改成q=p->next;
free(q);
//不能用free(p->next),此时p->next已经被修改,因此用q记住原来的p->next,再free掉那块空间
}
//delete为关键字,不能作为函数名字
void sort(nodeptr phead,int len)
{
int i, j, tmp;
len = length(phead);
nodeptr p, q;
for (i = 0,p=phead->next; i < len - 1; i++,p=p->next)
{
for (j = 0,q=phead->next; j < len - 1 - i; j++,q=q->next)
{
if (q->data > q->next->data)
{
tmp = q->data;
q->data = q->next->data;
q->next->data = tmp;
}
}
}
}
//类比于冒泡排序
int main()
{
nodeptr phead = creatlist(); int i;
for (i= 5; i >0; i--)
{
add(phead, i,6-i);
print(phead);
}
add(phead, 6, 6);
print(phead);
sort(phead,length(phead)); print(phead);
for (i = 5; i > 0; i--)
{
deletenode(phead, i);
print(phead);
}
deletenode(phead, 1);
print(phead);
}
//问题1:
//next不是node成员
//解决:
//将typedef struct node
//{
// int data;
// nodeptr next;
//}node, * nodeptr;
//改为:
//typedef struct node
//{
// int data;
// struct node* next;
//}node, * nodeptr;
//因为在建立next的时候,还未知nodeptr是什么类型
运行结果:
creating success
5
54
543
5432
54321
543216
123456
12346
1236
126
16
6
the list is empty