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