2012.8.8

来源:互联网 发布:开服装店知乎 编辑:程序博客网 时间:2024/05/01 09:31

数据结构:线性表——单链表(用时两个半小时,完成)

头文件 LinList.h
typedef struct Node
{
 DataType data;
 struct Node *next;
} SLNode;

void ListInitiate(SLNode **head)
{
 *head = (SLNode *)malloc( sizeof(SLNode) );
 (*head)->next = NULL;

}

int ListLength(SLNode *head)
{
 int size=0;
 SLNode *p = head;

 while (p->next != NULL)
 {
  p = p->next;
  size++;
 }
 return size;
}

int ListInsert(SLNode *head, int i, DataType x)
{
 SLNode *p,*q;
 int j;

 p = head;
 j = -1;

 while ( (p->next != NULL) && (j < i-1) )
 {
  p = p->next;
  j++;
 }

 if (j != i-1)
 {
  printf("参数错误!\n");
  return 0;
 }

 q = (SLNode *)malloc(sizeof(SLNode));
 q->data = x;

 q->next = p->next;
 p->next = q;

 return 1;
}

int ListDelete(SLNode *head, int i, DataType *x)
{
 SLNode *p, *q;
 int j;

 p = head;
 j = -1;

 while ( (p->next != NULL) && (p->next->next != NULL) && (j < i-1) )
 {
  p = p->next;
  j++;
 }

 if (j != i-1)
  printf("参数错误!\n");

 q = p->next;
 *x = q->data;

 p->next = p->next->next;
 free(q);

 return 1;
}

int ListGet(SLNode *head, int i, DataType *x)
{
 SLNode *p;
 int j;

 p = head;
 j = -1;

 while ( (p->next != NULL) && (j < i) )
 {
  p = p->next;
  j++;
 }

 if (j != i)
 {
  printf("参数错误!\n");
  return 0;
 }

 *x = p->data;

 return 1;
}

void Destroy(SLNode **head)
{
 SLNode *p,*q;
 p = *head;

 while (p->next != NULL)
 {
  q = p;
  p = p->next;
  free(q);
 }
 
 *head = NULL;
}

LinList.cpp
#include <stdio.h>
#include <malloc.h>
#include <iostream>

typedef int DataType;
#include "LinList.h"

int main()
{
 SLNode *head;
 int i,x;

 ListInitiate(&head);
 for (i=0; i<10; i++)
  ListInsert(head,i,i+1);
 ListDelete(head,4,&x);
 
 for (i=0; i<ListLength(head); i++)
 {
  ListGet(head,i,&x);
  printf("%d  ",x);
 }

 Destroy(&head);

 system("pause");
}

线性表中,顺序表与单链表在主函数上的使用类同,但头文件差别较大,顺序表更多的是对指定大小的空间

进行操作(数组),而链表则是动态分配内存空间然后使用。

计算机资讯:Geek(用时两个半小时,完成)