问题遇到的现象和发生背景
将两个链表中元素交错输出,却只输出前两个元素
问题相关代码
错误应该在braid函数中
#include <stdio.h>
#include <stdlib.h>
typedef struct Node Node;
struct Node {
int value;
struct Node *next;
};
Node* createListFromVector(int nums[], int n);
void printList(Node* list);
int sumOfElementsIn(Node* list);
Node* lastElementOf(Node* list);
Node* concat(Node* one, Node* two);
Node* reverse(Node*list);
Node* braid(Node *list,Node *rev);
int main(int argc, char const *argv[])
{
int nums[100] = {1, 8, 2, 7, 5, 3, 9, 0, 4, 6};
Node* list = createListFromVector(nums, 5);
Node* listRev = createListFromVector(nums, 5);
printList(list);
printf("\n");
listRev = reverse(list);
printList(listRev);
printf("\n");
list=braid(list,listRev);
printList(list);
// Node* fullList = createListFromVector(nums, 10);
// list = concat(list, fullList);
// printList(list);
// printf("sum = %d\n", sumOfElementsIn(list));
// printf("last value = %d\n", (lastElementOf(list))->value);
return 0;
}
Node* braid(Node *list,Node *rev)
{
Node *p=NULL,*temp=NULL;
for(p=list;p!=NULL;p=p->next->next)
{
temp=rev->next;
rev->next=p->next;
p->next=rev;
rev=temp;
}
return list;
}
Node* reverse(Node*list)
{
if(!list)
return NULL;
Node *prev=NULL,*curr=list,*temp;
while (curr)
{
temp=curr->next;
curr->next=prev;
prev=curr;
curr=temp;
}
return prev;
}
Node* concat(Node* one, Node* two)
{
if (one == NULL) {
return two;
}
lastElementOf(one)->next = two;
return two;
}
Node* lastElementOf(Node* list)
{
if (list == NULL) {
printf("No element.\n");
return NULL;
}
Node* result = list;
while (result->next != NULL) {
result = result->next;
}
return result;
}
int sumOfElementsIn(Node* list)
{
Node* curr;
int sum = 0;
for (curr = list; curr != NULL;
curr = curr->next) {
sum += curr->value;
}
return sum;
}
Node* createListFromVector(int* nums, int n)
{
if (n < 1) {
return NULL;
}
Node* head = (Node *)malloc(sizeof(Node));
head->value = nums[0];
head->next = NULL;
Node* curr = head;
for (int i = 1; i < n; i++) {
Node* newNode = (Node *)malloc(sizeof(Node));
newNode->value = nums[i];
newNode->next = NULL;
curr->next = newNode;
curr = newNode;
}
return head;
}
void printList(Node* list)
{
Node* curr;
for (curr = list; curr != NULL;
curr = curr->next) {
printf("%d\n", curr->value);
}
}
运行结果及报错内容
第三段运行结果为1,5
我的解答思路和尝试过的方法
braid函数编写思路
我想要达到的结果
第三段期望输出结果为
1 5 8 7 2 2 7 8 5 1