读书人

帮帮小弟我~还在学习中

发布时间: 2012-03-07 09:13:51 作者: rapoo

帮帮我~~还在学习中
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;} 

读书人网 >C语言

热点推荐