- <span style="font-family: 'microsoft yahei'; background-color: rgb(255, 255, 255);">【项目3 - 单链表应用】 </span>
算法的建立就是为了应用所服务的,学会方法,真正能应用才是王道。
应用要求如下:
完成下面的应用时,除项目中给出的特殊要求,其余工作均可利用项目2完成的算法支持。
1、设计一个算法,将一个带头结点的数据域依次为a1,a2,…,an(n≥3)的单链表的所有结点逆置,即第一个结点的数据域变为an,…,最后一个结点的数据域为a1。实现这个算法,并完成测试。
提示:实现算法时,可以设计下面的函数:void Reverse(LinkList *&L)
2、已知L1和L2分别指向两个单链表的头结点,且已知其长度分别为m、n,请设计算法将L2连接到L1的后面。实现这个算法,完成测试,并分析这个算法的复杂度。
提示:实现算法时,可以设计下面的函数:void Link(LinkList &L1, LinkList &L2)
3、设计一个算法,判断单链表L是否是递增的。实现这个算法,并完成测试。
本次实践用到的算法库单击这里参考(包含头文件Linklist.h)
1.
实现源代码如下:
- <span style="font-family:SimHei;font-size:12px;">
-
-
-
-
-
-
-
-
- #include <stdio.h>
- #include <malloc.h>
- #include "Linklist.h"
- void Reverse(LinkList *&L)
- {
- LinkList *p=L->next,*q;
- L->next=NULL;
- while (p!=NULL)
- {
- q=p->next;
- p->next=L->next;
- L->next=p;
- p=q;
- }
- }
-
- int main()
- {
- LinkList *L;
- ElemType a[]= {1,3,5,7, 2,4,8,10};
- CreateListR(L,a,8);
- printf("L:");
- DispList(L);
- Reverse(L);
- printf("逆置后L: ");
- DispList(L);
- DestroyList(L);
- return 0;
- }</span>
运行结果截图如下:
2.
实现源代码如下:
- <span style="font-family:SimHei;font-size:12px;">
-
-
-
-
-
-
-
-
- #include <stdio.h>
- #include <malloc.h>
- #include "linklist.h"
-
- void Link(LinkList *&L1, LinkList *&L2)
- {
- LinkList *p = L1;
- while(p->next != NULL)
- p = p->next;
- p->next = L2->next;
- free(L2);
- }
-
- int main()
- {
- LinkList *A, *B;
- int i;
- ElemType a[]= {1,3,2,9};
- ElemType b[]= {0,4,7,6,5,8};
- InitList(A);
- for(i=3; i>=0; i--)
- ListInsert(A, 1, a[i]);
- InitList(B);
- for(i=5; i>=0; i--)
- ListInsert(B, 1, b[i]);
- Link(A, B);
- printf("A:");
- DispList(A);
- DestroyList(A);
- return 0;
- }</span>
运行结果截图如下:
3.
实现源代码如下:
-
-
-
-
-
-
-
-
-
- #include <stdio.h>
- #include <malloc.h>
- #include "linklist.h"
-
- bool increase(LinkList *L)
- {
- LinkList *p = L->next, *q;
- if(p != NULL)
- {
- while(p->next != NULL)
- {
- q = p->next;
- if (q->data > p->data)
- p = q;
- else
- return false;
- }
- }
- return true;
- }
-
- int main()
- {
- LinkList *A, *B;
- int i;
- ElemType a[]= {1, 3, 2, 9};
- ElemType b[]= {0, 4, 5 ,6, 7, 8};
- InitList(A);
- for(i=3; i>=0; i--)
- ListInsert(A, 1, a[i]);
- InitList(B);
- for(i=5; i>=0; i--)
- ListInsert(B, 1, b[i]);
- printf("A: %c\n", increase(A)?'Y':'N');
- printf("B: %c\n", increase(B)?'Y':'N');
- DestroyList(A);
- DestroyList(B);
- return 0;
- }
运行结果截图如下: