修改程式範例: Ch4-3-2.c 為 Ch4-3-2e.c
1.修改 Ch4-3-2.c 中include的 “deleteNode.c”程式
2.將”情況2: 刪除最後一個節點”及”情況3: 刪除中間節點 “的程式碼判
斷改為同時指向 ptr->next.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
struct Node
{
int data;
struct Node *next;
};
typedef struct Node LNode;
typedef LNode *List;
List first = NULL;
extern void creatList(int len, int *array);
extern int isListEmpty();
extern void printList();
extern List searchNode(int d);
extern int deleteNode(List ptr);
extern void insertNode(List ptr, int d);
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
void createList(int len, int *array)
{
int i;
List newnode;
for ( i = 0; i < len; i++ )
{
newnode = (List) malloc(sizeof(LNode));
newnode->data = array[i];
newnode->next = first;
first = newnode;
}
}
int isListEmpty()
{
if ( first == NULL ) return 1;
else return 0;
}
void printList()
{
List current = first;
while ( current != NULL )
{
printf("[%d]", current->data);
current = current->next;
}
printf("\n");
}
List searchNode(int d)
{
List current = first;
while ( current != NULL )
{
if ( current->data == d )
return current;
current = current->next;
}
return NULL;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
int deleteNode(List ptr)
{
List current = first;
int value = ptr->data;
if ( isListEmpty() )
return -1;
if (ptr==first || ptr==NULL) {
first = first->next;
} else {
while (current->next!=ptr)
current = current->next;
current->next = ptr->next;
}
free(ptr);
return value;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#include <stdio.h>
#include <stdlib.h>
#include "Ch4-3.h"
#include "createList.c"
#include "deleteNode.c"
int main()
{
int temp;
int data[6]={ 1, 2, 3, 4, 5, 6 };
List ptr;
createList(6, data);
printf("原來的串列: ");
printList();
temp = 0;
while ( temp != -1 )
{
printf("請輸入刪除的郵寄編號(-1結束) ==> ");
scanf("%d", &temp);
if ( temp != -1 )
{
ptr = searchNode(temp);
if ( ptr != NULL )
{
temp = deleteNode(ptr);
printf("刪除節點: %d\n", temp);
printf("刪除後串列: ");
printList();
}
}
}
system("PAUSE");
return 0;
}
|
評分: ★★★★
回覆刪除creatList與createList不同