首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

帮帮小弟我~还在学习中

2012-03-07 
帮帮我~~还在学习中1,给出删除单链表中值为K的结点的前驱结点的算法.2,试给出实现删除单链表中值的相同的

帮帮我~~还在学习中
1,给出删除单链表中值为K的结点的前驱结点的算法.

2,试给出实现删除单链表中值的相同的多余接点的算法.

3,试给出依次输入单链表中所有数据元素的算法.

[解决办法]

C/C++ code
#include "stdlib.h"#include "stdio.h"struct node {    int data;    struct node* next;};struct node* build_link(int size) {    struct node* head = 0;    struct node* temp = 0;    struct node* prev = 0;    while (size--) {        temp = (struct node*)malloc(sizeof(struct node));        if (!head)            head = temp;        if (prev)            prev->next = temp;        prev = temp;    }    temp->next = 0;    return head;}/*1,给出删除单链表中值为K的结点的前驱结点的算法.*/int delete_prev_node(struct node* h, int K) {    struct node* t = h;    struct node* p = 0;    if (h == 0)        return 0;    while (t != 0) {        if (t->data == K) {            if (p == 0)                return 0;            p->data = t->data;            p->next = t->next;            free(t);            t = p->next;            continue;        }        p = t;        t = t->next;    }    return 0;}/*2,试给出实现删除单链表中值的相同的多余接点的算法.*/void delete_same(struct node* h){    struct node* t = h;    if (h == 0)        return;    while (t != 0)    {        struct node* a = t->next;        struct node* p = t;        while (a != 0)        {            if (a->data == t->data)            {                p->next = a->next;                free(a);                a = p->next;                continue;            }            p = a;            a = a->next;        }        t = t->next;    }}/*3,试给出依次输入单链表中所有数据元素的算法.*/void input_link(struct node* h){    struct node* t = h;    int i = 0;    while (t)     {        printf("input node-%d 's data : ", i++);        scanf("%d", &(t->data));        t = t->next;    }}void print_link(struct node* h){    struct node* t = h;    printf("the link is : ");    while (t)    {        printf("%d ", t->data);        t = t->next;    }    printf("\n");}int main(){    struct node* h = 0;    int s = 0;    int t = 0;    printf("please input the size of the link you want to build : ");    scanf("%d", &s);    if ((h = build_link(s)) == 0)    {        printf("build link error!!\n");        return 1;    }    input_link(h);    print_link(h);    delete_same(h);    printf("after delete the same node\n");    print_link(h);    printf("please input the value K to remove it's prev node : K = ");    scanf("%d", &t);    delete_prev_node(h, t);    print_link(h);    return 0;} 

热点排行