目錄表

國立屏東商業技術學院 資訊工程系 程式設計(二)

作業15

鏈結串列的實作


turnin code c.hw15

due date: May 27, 23:59

目的

練習使用鏈結串列的實作

第1題

參考下面的Makefile

main:   linkedlist.o main.c
        cc main.c linkedlist.o -o main
 
linkedlist.o:      linkedlist.c linkedlist.h
        cc -c linkedlist.c
 
clean:
        rm -f *.*~ *~ *.o main

將鏈結串列的宣告置於linkedlist.h中

struct node
{
  int value;
  struct node *next;
};
 
typedef struct node Node;
 
void showANode(Node *p);
void showAllNodes();
Node *getFirst();
Node *getLast();
int getSize();
int isEmpty();
Node *createANode(int v);
void addFirst(int v);
void addLast(int v);
void removeFirst();
void removeLast();
Node *search(int v);
Node *removeANode(int v);
int replace(int v, int newV);

main.c的內容如下:

#include <stdio.h>
#include <stdlib.h>
#include "linkedlist.h"
 
int main()
{
  Node *n;
 
  if(isEmpty())
  {
    printf("Empty\n");
  }
 
  showAllNodes();
 
  printf("add 3\n");
  addLast(3);
  printf("add 7\n");
  addFirst(7);
  printf("add 5\n");
  addLast(5);
  printf("add 6\n");
  addFirst(6);
 
  printf("replace 3 by 9\n");
  replace(3, 9);
 
  showAllNodes();
 
  printf("The first data is ");
  showANode(getFirst());
  printf("\n");
 
  printf("The last data is ");
  showANode(getLast());
  printf("\n");
 
  printf("The number of data is %d\n", getSize());
 
  printf("Is 7 in the linked list?\n");
  n=search(7);
  if(n!=NULL)
  {
    printf("Yes.\n");
    printf("The value next to 7 is ");
    n= n->next;
    showANode(n);
  }
  printf("\n");
  return 0;
}

請參考第19課的程式,完成linkedlist.c的實作。以make完成編譯後,執行./main可得到以下的結果:

[23:35 user@ws hw15]$ ./main 
Empty
NULL
add 3
add 7
add 5
add 6
replace 3 by 9
6-->7-->9-->5-->NULL
The first data is 6
The last data is 5
The number of data is 4
Is 7 in the linked list?
Yes.
The value next to 7 is 9
[23:35 user@ws hw15]$

注意: