請資料結構程式高手解答
題目:
1.請使用鏈結串列資料結構完成作業。
2.使用者可以選擇『1.新增節點』或『2.刪除節點』兩種功能。
3.選擇功能後輸入數字。新增節點則是在鏈結串列中找出適當的位置(由小到大排列),並將節點插入。刪除節點則是在鏈結串列中找出該筆資料,並將節點刪除。
4.執行功能之後將鏈結串列完整輸出,並再次回到使用者選擇步驟。
範例:
原鏈結串列
ptr→5口→10 NULLL
新增節點,數字7。
ptr→5口→7口→10 NULLL
刪除節點,數字5。
ptr→7口→10 NULLL
<口是空格的意思>
請問這個程式怎麼寫或是貼程式碼上來
1 則回答
最佳解答
#include <stdio.h>
#include <stdlib.h>
typedef struct node *NodePtr;
struct node
{
int data;
NodePtr next;
};
NodePtr InsertList(NodePtr head, int num)
{
NodePtr ptr,pre,suc;
ptr = (NodePtr)malloc(sizeof (struct node));
ptr->data =num;
ptr->next =NULL;
if(head==NULL)
return ptr;
if(head->data > num)
{
ptr->next = head;
return ptr;
}
pre = head;
suc = head->next;
while (suc!=NULL)
{
if (suc->data > num) break;
pre = suc;
suc = suc->next;
}
pre->next = ptr;
ptr->next = suc;
return head;
}
NodePtr DeleteList(NodePtr head, int num)
{
NodePtr prePtr, nextPtr,ptr;
if (head==NULL) return NULL;
while (head->data==num)
{
ptr = head;
head = head->next;
free(ptr);
if (head==NULL) return NULL;
}
prePtr = head;
nextPtr = head->next;
while (nextPtr !=NULL)
{
if(nextPtr->data==num)
{
ptr=nextPtr;
prePtr->next = nextPtr->next;
nextPtr = prePtr->next;
free(ptr);
}
else if (nextPtr->data > num)
break;
else
{
prePtr = nextPtr;
nextPtr= prePtr->next;
}
}
return head;
}
int PrintList(NodePtr head)
{
printf("ptr ");
while (head!=NULL)
{
printf("→ %d",head->data);
head = head->next;
}
printf("→ NULL\n");
return 0;
}
int main()
{
char ch;
int num;
NodePtr head;
head=NULL;
do
{
system("cls");
printf("1.新增節點\n");
printf("2.刪除節點\n");
printf("E.離開\n");
printf("按1或2或E: ");
ch = getchar();
switch(ch)
{
case '1':
printf("輸入新增數值: ");
scanf("%d", &num);
head=InsertList(head,num);
PrintList(head);
system("pause");
break;
case '2':
printf("輸入刪除數值: ");
scanf("%d", &num);
head=DeleteList(head,num);
PrintList(head);
system("pause");
break;
}
} while (ch!='E' && ch!='e');
printf("結束. ");
system("pause");
return 0;
}