数据结构结构中单链表创建增加节点、求表长、查找并定位链表节点数据、插入链表节点、删除链表节点,最后打印出来;可直接复制代码运行并检验;
注意:这里的代码编译环境是vs2013,如果你在其他的编译环境可以先把"scanf_s"改成"scanf"
#include"stdio.h"
#include"stdlib.h"
typedef struct node * pointer;
typedef struct node{
char data;
pointer next;
}list;
//创建增加节点
pointer creat()
{
pointer head, rear, s;
char a;
head = (struct node*)malloc(sizeof(struct node));
rear = head;
while (scanf_s("%c", &a),a != '$'){
s = (struct node*)malloc(sizeof(struct node));
s->data = a;
rear->next = s;
rear = s;
}
rear->next= NULL;
return head;
}
//求表长
int length(pointer head)
{
pointer p;
int n = 0;
p = head->next;
while (p != NULL){
p = p->next;
n++;
}
return n;
}
//查找并定位
pointer locate(pointer head, char c,int * f)
{
pointer p;
p = head->next;
while ( p != NULL){
(*f)++;
if (p->data == c) break;
p = p->next;
}
if (*f <= 0) p=NULL;
return p;
}
//插入
void insert(pointer head, char c, int i)
{
pointer p, s;
int j = 1;
if (i <= 0) return;
s = (struct node *)malloc(sizeof(struct node));
s->data = c;
p = head->next;
while (j < i-1 && p->next != NULL){
p = p->next;
j++;
}
s->next = p->next;
p->next = s;
printf("hello\n");
return;
}
//删除
void del(pointer head, int i)
{
pointer s, p;
int j = 1;
p = head->next;
if (i <= 0) return;
while (j < i - 1 && p != NULL){
j++;
p = p->next;
}
s = p->next;
p->next = s->next;
free(s);
return;
}
void main()
{
pointer head,p,find;
int l,f=0;
head=creat();//建表
p = head->next;
//打印出表数据
do{
printf("%c", p->data);
p = p->next;
}while(p!=NULL);
printf("\n");
p = head->next;
//求表长
l = length(head);
printf("表长:%d\n", l);
//定位查找
find = locate(head, 'h',&f);
if (find != NULL)
{
printf("查找字符%c,定位在第%d个\n", find->data, f);
}
else
{
printf("查找失败!\n");
}
//插入并重新打印
insert(head, '*', 3);
printf("插入后新链表数据:\n");
do{
printf("%c", p->data);
p = p->next;
} while (p != NULL);
printf("\n");
p = head->next;
//删除
del(head, 4);
printf("删除后新链表数据:\n");
do{
printf("%c", p->data);
p = p->next;
} while (p != NULL);
printf("\n");
p = head->next;
}