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;
}