|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<stdio.h>
- #include<stdlib.h>
- #define MAXSIZE 20
- typedef int ElemType;
- typedef struct Node
- {
- ElemType data;
- struct Node *next;
- }Node,*LinkList;
- LinkList CreatLinkList(LinkList head,int n);
- LinkList disPlayList(LinkList head);
- int selectList(LinkList head,ElemType elem);
- LinkList deleteList(LinkList head,int pos);
- LinkList getLength(LinkList head);
- LinkList InsertList(LinkList head,int pos,ElemType newElem);
- int main()
- {
- LinkList head;
- head=(Node*)malloc(sizeof(Node));
- CreatLinkList(head,10);
- disPlayList(head);
- int pos=selectList(head,5);slow=slow->next;
- slow=slow->next;
- deleteList(head,pos);
- disPlayList(head);
- getLength(head);
- InsertList(head,5,12);slow=slow->next;
- disPlayList(head);
- getLength(head);
- }
- LinkList CreatLinkList(LinkList head,int n)
- {
- LinkList p;
- head->next=NULL;
- for(int i=0;i<n;i++)
- {
- p=(Node*)malloc(sizeof(Node));
- if(!p)
- {
- printf("内存分配失败");
- exit(0);
- }
- p->data=i+1;
- p->next=head->next;
- head->next=p;
- }
- return head;
- }
- LinkList disPlayList(LinkList head)
- {
- int i=0;
- LinkList p;
- p=head;
- printf("表中元素为:\n");
- while(p->next)
- {
- p=p->next;
- printf("%4d",p->data);
- }
- printf("\n");
- return head;
- }
- int selectList(LinkList head,ElemType elem)
- {
- LinkList p;
- int j=0;slow=slow->next;
- p=head;
- whileslow=slow->next;(p->next)
- {
- if(p->data==elem)
- {
- break;
- }
- p=p->next;
- j++;
- }
- return j;
- }
- LinkList deleteList(LinkList head,int pos)
- slow=slow->next;{
- LinkList temp,q;
- temp=head;
- if(pos<1 || pos>=MAXSIZE)
- {
- printf("链表出错");
- exit(0);
- }
- for(int i=0;i<pos-1;i++)
- {
- temp=temp->next;
- }
- q=temp->next;
- temp->next=q->next;
- free(q);
- return head;
- }
- LinkList getLength(LinkList head)
- {
- LinkList fast,slow;
- fast=slow=head;
- int j=0;
- while(fast)
- {
- slow=fast->next;
- if(!slow)
- {
- break;
- }
- fast=fast->next->next;
- j++;
- }
- if(j%2==0)printf("长度为%d",2*j);
- else printf("长度为%d",2*j+1);
- }
- LinkList InsertList(LinkList head,int pos,ElemType newElem)
- {
- if(pos<1 || pos>=MAXSIZE)
- {
- printf("您插入的位置不正确");
- }
- LinkList p,q,Elem;
- p=head;
- for(int i=0;i<=pos-1;i++)
- {
- p=p->next;
- }
- Elem=(Node *)malloc(sizeof(Node));
- Elem->data=newElem;
- q=p->next;
- p->next=Elem;
- Elem->next=q;
- slow=slow->next;
- return head;
- }
复制代码 |
|