- //
- // main.c
- // 静态链表
- //
- #include <stdio.h>
- #define MAXSIZE 15
- #define OK 1
- #define ERROR 0
- #define TRUE 1
- #define FALSE 0
- typedef int Status;
- typedef int ElemType;
- typedef struct{
- ElemType data;
- int cur;
- }Component,StaticList[MAXSIZE];
- /*初始化*/
- Status InitList(StaticList space){
-
- for (int i = 0; i <= MAXSIZE -1; i++) {
- space[i].cur = i + 1;
- space[i].data = 0;
- }
- space[MAXSIZE - 1].cur = 0;
-
- return OK;
- }
- /*插入*/
- int InsertList(StaticList space,ElemType e){
- int i = space[0].cur;
- //顺序插入,第一次的首地址指向1
- if (!space[MAXSIZE-1].cur) {
- space[MAXSIZE-1].cur = 1;
- }
-
- if (space[0].cur) {
- space[0].cur = space[i].cur;
- space[i].data = e;
- }
- return i;
- }
- /*demo 插入*/
- int Malloc_SLL(StaticList space)
- {
- int i = space[0].cur;
-
- if (space[0].cur) {
- space[0].cur = space[i].cur;
- }
-
- return i;
- }
- /*指定位置上插入元素*/
- Status ListInsert(StaticList space,int i,ElemType e){
- int j,k,l,length;
-
- k = MAXSIZE - 1;
- length = ListLength(space);
- if (i < 1 || i > length - 1) {
- return ERROR;
- }
-
- j = Malloc_SLL(space);
-
- if (j) {
- space[j].data = e;
- for (l = 1; l < i-1; l++) {
- k = space[k].cur;
- }
- space[j].cur = space[k].cur;
- space[k].cur = j;
- }
-
- return OK;
- }
- int ListLength(StaticList list){
- int length = 0;
- int k = MAXSIZE - 1;
- for (int i = 0; i < MAXSIZE - 1; i++) {
- if (k == list[0].cur) {
- break;
- }
- length++;
- k = list[k].cur;
- }
-
- return length;
- }
- /*print*/
- void PrintAllElem(StaticList space)
- {
- int k = MAXSIZE - 1;
-
- for (int i = 0; i < MAXSIZE - 1; i++) {
- printf("position is %d,data is %d,cru is %d\n",k,space[k].data,space[k].cur);
- k = space[k].cur;
- }
- }
- int main(int argc, const char * argv[])
- {
- StaticList myspace;
- InitList(myspace);
-
- InsertList(myspace, 11);
- InsertList(myspace, 22);
- InsertList(myspace, 33);
- InsertList(myspace, 44);
- InsertList(myspace, 55);
-
- ListInsert(myspace, 3, 66);
- ListInsert(myspace, 3, 77);
-
- InsertList(myspace, 88);
-
- PrintAllElem(myspace);
-
- printf("length is %d\n",ListLength(myspace));
- printf("last cur is %d\n",myspace[0].cur);
- return 0;
- }
复制代码
ListInsert,这个函数调用完毕后,输出链表,觉得有些问题,想来是因为造成了有两个节点指向了一个节点,但是不知道怎么修正。望大神能给指出一下。 |