//單向鏈錶
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct link *addnote();
int delt(struct link *head);
int out(int i,struct link *head);
struct link
{
int data;
struct link *next;
};
int main()
{
int i,j = 0;
struct link *head = NULL;
printf("請問要建立幾個結點:");
scanf("%d",&i);
printf("\n");
while(i > 0)
{
head = addnote(head);
i--;
j++;
}
out(j,head);
delt(head);
out(j-1,head);
}
int delt(struct link *head)
{
int i;
char asw[5] = "0";
struct link *pr = head,*q;
printf("\n是否需要刪除節點?(Yeah / No)\n");\
scanf("%s",asw);
if(strcmp(asw,"Yeah") == 0)
{
printf("請問需要刪除第幾個節點(輸入序號): ");
scanf("%d",&i);
while(i-2 > 0)
{
pr = pr -> next;
}//找到這個指針的前一個節點
//第一次指向第二個節點,所以要循環i-2次
q = pr -> next;
pr -> next = pr -> next -> next;
free(q);
}
return 0;
}
struct link *(addnote(struct link *head))
{
int data;
struct link *p =NULL,*pr = head;
p = (struct link*)malloc(sizeof(struct link));
if(head == NULL)
{
head = p;
}
else
{
while(pr -> next != NULL)
{
pr = pr -> next;
}
pr -> next = p;
}//如果頭節點不是空節點,在尾節點與頭節點之間添加節點
printf("請輸入數據:");
scanf("%d",&data);//第一次是在頭節點中輸入數據
p -> data = data;
p -> next = NULL;//第一次p移動頭節點的下一位添加尾節點
return head;
}
int out(int i,struct link *head)
{
int j = 1;
struct link *p = head;
printf("\n");
while(i > 0)
{
printf("第%d個數據為%d\n",j,p -> data);
p = p -> next;
i--;
j++;
}
return 0;
}
運行結果: