#include <string.h>
#include <stdio.h>
typedef struct _node
{
char *data;
int length;
} Node;
int main()
{
Node head = {0};
head.data = (char *)malloc(100 * sizeof(char));
int i = 0;
char ch;
while (i < 100 && (ch = getchar()) != '\n')
{
if (ch == ' ')
continue;
head.data[i++] = ch;
}
head.length = i;
for (i = 0; i < head.length - 1; i++)
{
for (int j = i + 1; j < head.length; j++)
{
if (head.data[i] == head.data[j])
{
memcpy(&head.data[j], &head.data[j + 1], head.length - j);
head.length--;
i--;
}
}
}
char *p = (char *)malloc(head.length * sizeof(char));
memcpy(p, head.data, head.length);
free(head.data);
head.data = p;
for (i = 0; i < head.length; i++)
{
printf("%c ", head.data[i]);
}
return 0;
}
供参考:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int DataType;
typedef struct node {
DataType data;
struct node* link;
}Node;
//初始化空链表
Node* initLinkList() {
Node* head = (Node*)malloc(sizeof(Node)); //头节点
if (head == NULL) {
printf("链表初始化失败\n");
return NULL;
}
head->link = NULL;
return head;
}
Node* creatNode(DataType ele) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("节点创建失败\n");
return NULL;
}
newNode->data = ele;
newNode->link = NULL;
return newNode;
}
Node* getTail(Node* L) {//获取尾指针
Node* pMove = L;
while (pMove->link) {
pMove = pMove->link;
}
return pMove;
}
void tailInsert(Node* L, DataType ele) {
if (L == NULL) {
printf("链表未初始化\n");
return;
}
Node* newNode = creatNode(ele);
getTail(L)->link = newNode;
}
void deleteDuplicates(Node* L) //链表去重
{
if (L == NULL || L->link == NULL) return;
Node* p, * pnext, * pnextpre, * tmp;
p = L;
while (p->link)
{
pnextpre = p->link;
pnext = pnextpre->link;
while (pnext) {
if (p->link->data == pnext->data)
{
tmp = pnext;
pnextpre->link = pnext->link;
free(tmp);
pnext = pnextpre->link;
}
else{
pnextpre = pnext;
pnext = pnext->link;
}
}
p = p->link;
}
}
void Print(Node* L) {
Node* p = L->link;
if (!p) {
printf("NULL");
}
else {
while (p) {
printf(p == L->link ? "%d" : " %d", p->data);
p = p->link;
}
}
printf("\n");
}
int main()
{
int i;
srand((unsigned int)time(NULL));
Node* List = initLinkList();
for (i = 0; i < 20; i++)
tailInsert(List, rand() % 10);
Print(List);
deleteDuplicates(List);//去重
Print(List);
return 0;
}