#include<stdio.h>
#include<stdlib.h>typedef struct Node{ char data; Node *next;} Node,*LinkList;//初始化单链表
void InitList(LinkList *L){ *L=(LinkList)malloc(sizeof(Node)); (*L)->next=NULL;}//头插法建立单链表
void CreateFromHead(LinkList L){ Node *s; char c; int cp=1; while(cp){ scanf("%c",&c); if(c!='$') { s=(Node*)malloc(sizeof(Node)); s->data=c; s->next=L->next; L->next=s; } else cp=0; }}//尾插法建立单链表
void CreateFromTail(LinkList L){ Node *s; Node *r; char c; int cp=1; r=L; while(cp) { scanf("%c",&c); if(c!='$') { s=(Node*)malloc(sizeof(Node)); s->data=c; r->next=s; r=s; } else {cp=0;r->next=NULL;} }}//在单链表中查找第i个结点
Node* Get(LinkList L,int i){ int j; j=0; Node *p; p=L; if(i<=0)return NULL; while((p->next!=NULL)&&j<i) { p=p->next; j++; } if(i==j)return p; else return NULL;}//按值查找
Node* Locate(LinkList L,char c){ Node *p; p=L->next; while(p!=NULL) { if(p->data!=c) p=p->next; else break; } if(p==NULL)printf("未查找到!"); return p;}//求单链表长度
int ListLength(LinkList L){ Node *p; p=L->next; int j=0; while(p!=NULL) { p=p->next; j++; } return j;}//输出单链表中所有值
void Printff(LinkList L) { Node *p; p=L->next; while(p!=NULL) { printf("%c",p->data); p=p->next; } }//单链表插入操作void InsList(LinkList L,int i,char c){ Node *pre,*s; int k; if(i<=0)printf("ERROR!"); pre=L; k=0; while(pre!=NULL&&k<i-1) { pre=pre->next; k++; } if(!pre) { printf("插入位置不合理!"); } s=(Node*)malloc(sizeof(Node)); s->data=c; s->next=pre->next; pre->next=s; printf("插入成功!");}//单链表删除操作void DelList(LinkList L,int i){ Node *pre,*r; int k; pre=L; k=0; char c; while(pre->next!=NULL&&k<i-1) { pre=pre->next; k++; } if(!(pre->next)) { printf("删除位置不合理!\n"); } r=pre->next; pre->next=r->next; c=r->data; free(r); printf("删除的值为:%c\n",c); printf("删除成功!\n");} int main(){ LinkList *L; InitList(L); //CreateFromHead(*L); printf("请输入结点的值:\n"); CreateFromTail(*L);
int i;
printf("请输入你要查找的位置:\n"); scanf("%d",&i); Node *p=Get(*L,i); printf("第%d个结点值是:%c\n",i,*p); char c; char d=getchar(); printf("请输入你要查找的值:\n"); scanf("%c",&c); Node *q=Locate(*L,c); printf("搜索到%c\n",*q); printf("长度为:%d\n",ListLength(*L)); printf("请输入你要插入的位置和值:\n"); int h;char hh; scanf("%d %c",&h,&hh); InsList(*L,h,hh); printf("插入后链表为:\n"); Printff(*L); printf("\n"); printf("请输入你要删除的位置:\n"); int hhh; scanf("%d",&hhh); DelList(*L,hhh); printf("删除后链表为:\n"); Printff(*L); printf("\n"); return 0;}