学习笔记——C语言实现单链表的基本操作：创建、输出、插入结点、删除结点、逆序链表

474人阅读 评论(0)

***************************************************

***************************************************

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

typedef struct Node
{
int data;
struct Node *next;
}Lnode;

Lnode *createList();

int main()
{
int elem,position;

printf("Input the element and the position:/n");
scanf("%d %d", &elem, &position);

printf("After reversed:/n");

printf("Input the element you want to delete:/n");
scanf("%d",&elem);

return 0;
}

/*传入表头指针，打印链表*/
{

if (p == NULL)
{
printf("List is empty!/n");
return;
}
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("/n");
}

/*创建一个新链表，返回表头指针*/
Lnode *createList()
{
int data;

printf("Input integers,0 to break:/n");
scanf("%d",&data);

if (data != -1)
{
p->data = data;
}
else
{
}

while (1)
{
scanf("%d", &data);
if (data == -1)
{
break;
}

current = (Lnode *)malloc(sizeof(Lnode));
current->data = data;
p->next = current;
p = p->next;
}
p->next = NULL;

}

*将elem插入至第position个结点后，position<=0时，插入至头结点后
*/
{
Lnode *current, *p;
int i = position - 1;

/*找到第position个节点*/
while (i > 0 && current->next != NULL)
{
current = current->next;
i--;
}

if (i > 0)   //结点数小于输入的位置position
{
printf("Position is wrong!/n");
}

p = (Lnode *)malloc(sizeof(Lnode));
p->data = elem;
p->next = current->next;
current->next = p;

}

{
Lnode *ptemp;
int flag = 0;  //记录便表中elem的个数

while (1)
{
{
flag++;
free(p);
}
else
{
break;
}
}

while (p->next != NULL)
{
if (p->next->data == elem )
{
flag++;
ptemp = p->next;
if (p->next->next != NULL)
{
p->next = p->next->next;
free(ptemp);
ptemp = NULL;
}
else //最后一个结点
{
free(ptemp);
ptemp =NULL;
p->next = NULL;
break;
}
}
else  //没有删除结点时，查询下一个结点
{
p = p->next;
}
}
printf("%d number '%d' was found and deleted./n", flag, elem);
}

/*将链表逆序，该链表不带头结点。*/
{
Lnode *current, *pnext, *ptemp;

while (pnext != NULL)
{
ptemp = pnext->next;
pnext->next = current;
current = pnext;
pnext = ptemp;
}

}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：84659次
• 积分：1201
• 等级：
• 排名：千里之外
• 原创：7篇
• 转载：181篇
• 译文：0篇
• 评论：3条
阅读排行
评论排行
最新评论