gpt4 book ai didi

c - 拆分链表

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:55 25 4
gpt4 key购买 nike

为什么这个程序中的拆分列表总是空的? (它源自链接列表上 Wikipedia 页面上的代码。)

/* 
Example program from wikipedia linked list article
Modified to find nth node and to split the list
*/

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

typedef struct ns
{
int data;
struct ns *next; /* pointer to next element in list */
} node;

node *list_add(node **p, int i)
{
node *n = (node *)malloc(sizeof(node));
if (n == NULL)
return NULL;

n->next = *p; //* the previous element (*p) now becomes the "next" element */
*p = n; //* add new empty element to the front (head) of the list */
n->data = i;

return *p;
}

void list_print(node *n)
{
int i=0;
if (n == NULL)
{
printf("list is empty\n");
}
while (n != NULL)
{
printf("Value at node #%d = %d\n", i, n->data);
n = n->next;
i++;
}
}

node *list_nth(node *head, int index) {
node *current = head;
node *temp=NULL;
int count = 0; // the index of the node we're currently looking at
while (current != NULL) {
if (count == index)
temp = current;
count++;
current = current->next;
}
return temp;
}
/*
This function is to split a linked list:
Return a list with nodes starting from index 'int ind' and
step the index by 'int step' until the end of list.
*/
node *list_split(node *head, int ind, int step) {
node *current = head;
node *temp=NULL;
int count = ind; // the index of the node we're currently looking at
temp = list_nth(current, ind);
while (current != NULL) {
count = count+step;
temp->next = list_nth(head, count);
current = current->next;
}

return temp; /* return the final stepped list */
}

int main(void)
{
node *n = NULL, *list1=NULL, *list2=NULL, *list3=NULL, *list4=NULL;
int i;
/* List with 30 nodes */
for(i=0;i<=30;i++){
list_add(&n, i);
}
list_print(n);

/* Get 1th, 5th, 9th, 13th, 18th ... nodes of n etc */

list1 = list_split(n, 1, 4);

list_print(list1);

list2 = list_split(n, 2, 4); /* 2, 6, 10, 14 etc */
list_print(list2);

list3 = list_split(n, 3, 4); /* 3, 7, 11, 15 etc */
list_print(list3);

list3 = list_split(n, 4, 4); /* 4, 8, 12, 16 etc */
list_print(list4);

getch();
return 0;
}

最佳答案

 temp = list_nth(current, ind);

while (current != NULL) {
count = count+step;
temp->next = list_nth(head, count);
current = current->next;
}

您找到了开始拆分的正确项目,但是看看从那时起 temp 发生了什么……您只分配给 temp->next。

您需要跟踪拆分列表的头部和插入新项目的尾部。

关于c - 拆分链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/324353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com