最近被问道一道挺有趣的算法题:采用递归的方式,将单链表中存储的重复数据删除,只保留第一次出现的数据所在结点。如链表中存储的数据是 1 9 9 8 8 8,最后剩下的是1 9 8. 下面是具体实现
//
// SingleLinkRecurse.c
//
//
// Created by yanbinbin.
//
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
void createList(LNode *node, int len){
int i;
int val;
LNode *tmp, *p;
printf("input current node's val: ");
scanf("%d", &val);
node->data = val;
node->next = NULL;
p = node;
for (i = 0; i < len-1; ++i) {
tmp = (LNode *)malloc(sizeof(LNode));
printf("input current node's val: ");
scanf("%d", &val);
tmp->data = val;
tmp->next = NULL;
p->next = tmp;
p = p->next;
}
}
LNode *recurseLNode(LNode *node, int len){
if(len == 1)
return node;
else{
LNode *tmp = node;
while(tmp != NULL){
while(tmp->next != NULL && tmp->next->data == node->data){
tmp->next = tmp->next->next;
--len;
}
tmp = tmp->next;
}
if(len > 1)
return recurseLNode(node->next, len-1);
else
return recurseLNode(node, len);
}
}
void printLNode(LNode *node){
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main(){
LNode node, *pnode=&node, *tmp;
int len = 6;
int i;
int val;
createList(pnode, len);
printLNode(pnode);
putchar('\n');
recurseLNode(pnode, len);
printLNode(pnode);
putchar('\n');
return 0;
}