c - 编写一个函数,该函数以链表为参数,并返回在原始链表中偶数位置找到的节点

标签 c

我无法让我的程序正常工作。我根本无法让它打印偶数节点。我对链表还很陌生。我让初始正常列表可以工作和打印,但甚至无法让其他函数调用/工作。

#include <stdio.h>
#include <stdlib.h>

typedef struct {

int data;
 struct node* next;

}node;

struct node* head;
struct node* evenHead;

node* copyEven(node *mylist)
 {
    node* newHead = NULL;
    node* temptr = NULL;
    int count = 1;

    for(temptr = mylist;  temptr->next != NULL; temptr = temptr->next){
        if ( count % 2 == 0){
            node* newNode = malloc(sizeof(node));
            newNode->data = temptr->data;
            if(newHead == NULL)
            {
                newHead = newNode;
            }
            for (temptr = newHead; temptr->next != NULL; temptr = temptr->next);
                node *ptr = (node*)malloc(sizeof(node));
                temptr->next = ptr;
                ptr->data = temptr->data;
                ptr->next = NULL;
        }
        count++;
    }
return newHead;
}

void Insert(int x)
{
node* temp = (node*)malloc(sizeof(node));
temp->data = x;
temp->next = head;
head = temp;
 }
void print()
 {
     node* temp = head;
    printf("List is : ");

    while(temp != NULL)
    {
        printf(" %d", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

void printEven()
{
    node* temp = evenHead;
    printf("even list is: ");

    while(temp != NULL)
    {
        printf(" %d", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

int main()
{

    head = NULL;
    evenHead= NULL;

    Insert(1);
    Insert(2);
    Insert(3);
    Insert(4);

    print();

    evenHead = copyEven(head);

     printEven();

    return 0;
 }

最佳答案

typedef struct node {
    int data;
    struct node* next;
} node;

node *copyEven(node *mylist){
    node *newHead = NULL, *temptr = NULL;
    int count = 1;

    while(mylist){
        if ( count % 2 == 0){
            node* newNode = malloc(sizeof(node));
            newNode->data = mylist->data;
            newNode->next = NULL;
            if(newHead == NULL){
                temptr = newHead = newNode;
            } else {
                temptr = temptr->next = newNode;
            }
        }
        count++;
        mylist = mylist->next;
    }
    return newHead;
}

关于c - 编写一个函数,该函数以链表为参数,并返回在原始链表中偶数位置找到的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25857094/

相关文章:

c - 为什么随机生成器只生成零

C-char指针和char指针字符串管理

c++ - 无法在 Windows 对话框上显示其他 unicode 东亚语言

c - 已知值的完美哈希

C: 将 argv[1] 转换为 double

c# - 从 C# 调用非托管代码

java - 使用 SHA1 从多个值计算聚合

使用 char 数组的 C 结构初始化

c - Winpcap MinGW编译错误

c - Redis 模块 RESTORE 命令调用