以下是“链表在指定节点后插入新元素”的简单示例:
1. 用c语言实现的版本
#include<stdio.h>
#include<stdlib.h>
typedef char datatype;
typedef struct node{
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 <(i - 1))
{
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");
}
运行结果如下图所示: