标签:
#include<stdio.h> #include<stdlib.h> struct LinkList { int data; struct LinkList *next; }; /*初始化链表*/ void init_list(LinkList **head) { *head=(LinkList *)malloc(sizeof(LinkList)); (*head)->next=NULL; } /*添加节点*/ void add_node(LinkList *head) { int x; LinkList *p,*q; q=head; printf("input add a data:"); scanf("%d",&x); while(q->next) q=q->next; p=(LinkList *)malloc(sizeof(LinkList)); p->data=x; p->next=q->next; q->next=p; } /*查找第i个节点,返回节点指针*/ LinkList *get_node(LinkList *head,int i) { LinkList *p=head; int j=0; while(p->next&&j<i) { p=p->next; j++; } if(j=i) return p; else return NULL; } /*按值查找节点,返回节点指针*/ void get_value(LinkList *head,int x) { int flag=0; LinkList *p=head; while(p->next) { p=p->next; if(p->data==x) { printf("%d\n",p->data); flag=1; break; } } if(!flag) printf("fail!\n"); } /*在链表中第i个节点之前插入节点*/ void insert_node(LinkList *head,int i,int x) { LinkList *p,*q; q=(LinkList *)malloc(sizeof(LinkList)); p=get_node(head,i-1); if(p) { q->next=p->next; p->next=q; q->data=x; } else printf("node in not exist!\n",i); } /*删除第i个节点*/ void delete_node(LinkList *head,int i) { LinkList *p,*q; p=get_node(head,i-1); q=get_node(head,i); if(q!=NULL) { p->next=q->next; free(q); } else printf("node in not exist!\n"); } /*修改链表中第i个节点*/ void modify_node(LinkList *head,int i,int x) { LinkList *p; p=get_node(head,i); if(p!=NULL) p->data=x; } /*显示链表中节点的数据*/ void show(LinkList *head) { LinkList *p; p=head->next; p=head; while(p->next) { p=p->next; printf("%2d",p->data); } printf("\n"); } int main() { struct LinkList *p; p=new LinkList; int ch,i,x; init_list(&p); add_node(p); while(1) { printf("******************************************************\n"); printf(" 1.add 2.get node by index 3.get node by value 4.insert \n 5.delete 6.modify 7.show 0.quit\n"); printf("******************************************************\n"); printf("please input your choice:"); scanf("%d",&ch); switch(ch) { case 1: add_node(p); break; case 2: { printf("input a number:"); scanf("%d",&i); printf("%d\n",(LinkList *)get_node(p,i)->data); break; } case 3: { printf("input value of x:"); scanf("%d",&x); get_value(p,x); break; } case 4: { printf("input values of i and x:"); scanf("%d%d",&i,&x); insert_node(p,i,x); break; } case 5: { printf("input value of i:"); scanf("%d",&i); delete_node(p,i); break; } case 6: { printf("input values of i and x:"); scanf("%d%d",&i,&x); modify_node(p,i,x); break; } case 7: show(p); break; case 0: exit(0); default:printf("error! please input again:\n"); break; } } return 0; }
标签:
原文地址:http://blog.csdn.net/yangshuangtao/article/details/44984283