C语言在buf末尾添加新元素,数据结构示例之链表在指定节点后插入新元素

以下是“链表在指定节点后插入新元素”的简单示例:

1. 用c语言实现的版本

#include

#include

typedef char datatype;

typedef structnode{

datatype data;

struct node *next;

} listnode;

typedef listnode *linklist;

listnode *p;

/* 创建链表,从表头插入新元素 */

linklist createlist(void)

{

char ch;

linklist head;

listnode *p;

head = NULL; /*初始化为空*/

printf("请输入字符序列:\n");

ch = getchar();

while (ch != '\n')

{

p = (listnode*)malloc(sizeof(listnode));/*分配空间*/

p->data = ch; /*数据域赋值*/

p->next = head; /*指定后继指针*/

head = p; /*head指针指定到新插入的结点上*/

ch = getchar();

}

return head;

}

/*在第i个节点后,插入x*/

int insertnode(linklist head, char x, int i)

{

int j = 0;

listnode * p, *s;

p = head;

while (p && j

{

p = p->next;

++j;

}

if (!p || j>(i - 1))

{

return -1;

}

s = (linklist)malloc(sizeof(listnode));

s->data = x;

s->next = p->next;

p->next = s;

return 1;

}

void main()

{

linklist list, head;

int i;

char x;

/* 创建链表,从表头插入新元素 */

list = createlist();

head = list;

printf("在插入前,输出链表中的元素\n");

do

{

printf("%c", head->data);

head = head->next;

} while (head != NULL);

printf("\n要在其后插入新节点的节点位置:");

scanf("%d", &i);

printf("要插入的值:");

getchar();

scanf("%c", &x);

/*在第i个节点后,插入x*/

int res = insertnode(list, x, i);

if (res == -1)

{

printf("插入失败\n");

}

else

{

printf("[%c]插入成功\n", x);

}

printf("在插入后,输出链表中的元素\n");

do

{

printf("%c", list->data);

list = list->next;

} while (list != NULL);

printf("\n");

}

运行结果如下图所示:

cd50c4c094fa5e11eda1ce211fe3279a.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值