https://blog.csdn.net/blessingxry/article/details/79445511
1.知識點:逆序建立鏈表+節點刪除?
2.題意:按照數據輸入的相反順序(逆位序)建立一個單鏈表,并將單鏈表中重復的元素刪除(值相同的元素只保留最后輸入的一個)?
3.注意事項:節點刪除時若刪除節點為尾節點的情況
代碼:
#include <stdio.h>
#include <stdlib.h>
typedef struct str
{int num;struct str *next;
} st;
st *meo(int n)///逆序記錄輸入的數值的函數
{int i;st *head, *p;head = (st *)malloc(sizeof(st));head -> next = NULL;for(i = 0; i < n; i++){p = (st *)malloc(sizeof(st));scanf("%d", &p->num);p -> next = head -> next;head -> next = p;}return head;
}
void pri(st *head)///順序輸出鏈表的數值的函數
{st *p;p = (st *)malloc(sizeof(st));p = head -> next;while(p != NULL){printf("%d%c", p->num, p->next == NULL? '\n': ' ');p = p -> next;}
}
void del(st *head, int n)///刪除鏈表中重復元素并輸出新的鏈表的函數
{int a;a = 0;st *p, *q, *t;p = head;while(p ->next != NULL){p = p -> next;t = p;q = p -> next;while(q != NULL){if(p->num == q->num)///刪除鏈表中的重復元素{a++;t -> next = q -> next;free(q);q = t -> next;continue;}t = q;q = t -> next;}}printf("%d\n", n - a);///輸出新鏈表的項數pri(head);///調用自定義的pri函數順序輸出新鏈表各項}
int main()
{int n;st *head;head = (st *)malloc(sizeof(st));scanf("%d", &n);head = meo(n);///調用逆序記錄函數printf("%d\n", n);pri(head);///調用順序輸出函數del(head, n);///調用刪除函數return 0;
}