递归删除单链表的重复结点

最近被问道一道挺有趣的算法题:采用递归的方式,将单链表中存储的重复数据删除,只保留第一次出现的数据所在结点。如链表中存储的数据是 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;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值