#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct node {
DataType data;
struct node *next;
}*LinkList,*pNode;
LinkList GetEmptyList() {
LinkList head = (pNode)malloc(sizeof(struct node));
head->data = 0;
head->next = NULL;
return head;
}
void CreateList(LinkList head, DataType a[],int n) {
int i;
pNode p = head;
for(i = 0; i < n; ++i) {
p->next = (pNode)malloc(sizeof(struct node));
p->next->data = a[i];
p = p->next;
}
p->next = NULL;
}
int LengthList(LinkList head) {
int len = 0;
pNode p = head->next;
while(p) { ++len; p = p->next; }
return len;
}
int InsertNode(LinkList head, DataType x, int pos) {
int i = 1,len = LengthList(head);
pNode tmp,p = head;
if(pos < 1) { printf("位置参数错误:%d。\n",pos); return 0; }
if(pos > len) { printf("位置参数超过表长,操作无效。\n"); return 0; }
while(p->next && pos > i) { ++i; p = p->next; }
tmp = (pNode)malloc(sizeof(struct node));
tmp->data = x;
tmp->next = p->next;
p->next = tmp;
return 1;
}
void ShowList(LinkList head) {
pNode p = head->next;
while(p) {
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkList head = GetEmptyList();
DataType arr[] = {3,6,8,9,2,13,45,62,33,45,68,90,22,31,42};
int n = sizeof(arr)/sizeof(arr[0]);
CreateList(head,arr,n);
printf("原表内容:\n");
ShowList(head);
InsertNode(head,100,5);
printf("\n在位置5插入100后:\n");
ShowList(head);
InsertNode(head,100,1);
printf("\n在位置1插入100后:\n");
ShowList(head);
return 0;
}
温馨提示:答案为网友推荐,仅供参考