- 註冊時間
- 2010-7-12
- 最後登錄
- 2024-5-30
- 主題
- 查看
- 積分
- 5
- 閱讀權限
- 15
- 文章
- 6
- 相冊
- 0
- 日誌
- 0
狀態︰
離線
|
#include <stdio.h>
#include <stdlib.h>
typedef struct listnode
{
int data; /*資料欄位*/
struct listnode *next;
} node;
int insertTail(node *head, int value)
{
node *newNode, *p = head;
if ((newNode = (node *) malloc(sizeof(node))) == NULL)
return 0;
newNode->data = value;
newNode->next = NULL;
while (p->next != NULL)
p = p->next;
p->next = newNode;
return 1;
}
void printList(node *p)
{
for (p = p->next; p != NULL; p = p->next)
printf("%d ", p->data);
}
void freeAllNode(node *head)
{
node *nextNode;
while (head != NULL)
{
nextNode = head->next;
free(head);
head = nextNode;
}
}
int insertAfter(node *p, int value)
{
node *newNode;
newNode = (node *) malloc(sizeof(node));
if (newNode == NULL)
return 0;
newNode->data = value;
newNode->next = p->next;
p->next = newNode;
return 1;
}
node *getPreNode(node *head, node *theNode)
{
node *p,*q;
p = head;
q = head->next;
while ((q != NULL) && (q != theNode))
{
p = q;
q = q->next;
}
if (q != NULL)
return p;
else
return NULL;
}
int deleteNode(node *head, node *theNode)
{
node *preNode;
if (head == theNode)
return 0;
preNode = getPreNode(head, theNode);
if (preNode == NULL)
return 0;
preNode->next = theNode->next;
free(theNode);
return 1;
}
int main(void)
{
int choose, i, insertdata, num;
node *listA, *p;
FILE *fin;
if ((fin = fopen("List.in", "r")) == NULL)
{
printf("File can not be opened, program terminate.");
exit(1);
}
listA = (node *) malloc(sizeof(node));
listA->next = NULL;
fscanf(fin, "%d", &insertdata);
while (!feof(fin))
{
insertTail(listA, insertdata);
fscanf(fin, "%d", &insertdata);
}
fclose(fin);
while (1)
{
printf("\n\n串列內容(Content of list) => ");
printList(listA);
printf("\n(1)附加節點(Append new node)\n(2)插入節點(Insert new node)\n(3)刪除節點(Delete node)\n(0)結束(exit) => ");
scanf("%d", &choose);
switch (choose)
{
case 0:
freeAllNode(listA); /*釋放所有節點*/
exit(0); /*結束程式*/
case 1:
printf("\n請輸入欲附加之資料(Input new data) => ");
scanf("%d", &insertdata);
insertTail(listA, insertdata);
break;
case 2:
printf("\n請輸入欲插入之資料(Input new data) => ");
scanf("%d", &insertdata);
printf("請輸入欲插入之位置(New Position) => ");
scanf("%d", &num);
for (i = 1, p = listA; i != num && p != NULL; p = p->next, i++);
if (p == NULL)
printf("插入失敗(Insert Failed)");
else if(insertAfter(p, insertdata) == 0)
printf("插入失敗(Insert Failed)");
break;
case 3:
printf("\n請輸入欲刪除之資料(data to be deleted) => ");
scanf("%d", &num);
for (i = 0, p = listA; p != NULL && p->data != num; p = p->next, i++);
if (p == NULL)
printf("此資料不在串列中(the data is not in list)");
else if(deleteNode(listA, p) == 0)
printf("刪除失敗(Delete Failed)");
break;
default:
printf("\n選項錯誤(Wrong option)!\n");
}
}
system("pause");
return(0);
}
這是原始程式
另外附加一個檔案 裡面打開是 1 2 3 4
5 6 7 8
請問如何改寫 能讓數字是由我們輸入 輸入完畢後數字會由小至大排列 |
|