【问题标题】:write linked list and make another one with reverse numbers of first list编写链表并使用第一个列表的反向编号创建另一个
【发布时间】:2020-02-29 11:53:25
【问题描述】:

所以我可以创建第一个链表,然后我可以将所有数字存储在一个具有数字大小的数组中,然后根据需要将它们全部放入第二个链表中,但是有没有什么好的算法可以做到这一点数组?

TY!

【问题讨论】:

  • 你可以直接从第一个链表做第二个链表,它会倒序,因为单链表是一个后进先出栈。
  • 您不应该使用带有链表的数组。它们是两个独立且不同的数据结构。与其用反向数字创建第二个列表,不如创建一个 双向链接 列表,该列表将允许正向和反向遍历 - 问题已解决。
  • 我想过,但还是希望有一些神秘的算法)
  • 这并不神秘。从头开始遍历第一个列表,并将每个项目插入新列表的头。不需要数组,你可能想多了。
  • @Weather Vane 对不起先生,那我应该使用递归吗?

标签: c data-structures linked-list


【解决方案1】:
//HERE WE GO!

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

struct listNode{
int value;
struct listNode *nextPtr;
};

typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;

void insert(ListNodePtr *sPtr, int value);
void copy(ListNodePtr *sPtr, int value);

void printList(ListNodePtr sPtr);
int main()
{
int value;

    ListNodePtr startPtr=0;
    ListNodePtr secondPtr=0;
    int tempValue;

    srand(time(0));
    for(int i=0;i<10;i++){
    value=rand()%15;
    insert(&startPtr,value);

    }
    while(startPtr!=0){
    tempValue=startPtr->value;
    copy(&secondPtr,tempValue);
    startPtr=startPtr->nextPtr;
    }

    printList(secondPtr);

}

void copy(ListNodePtr *sPtr, int value)
{
    ListNodePtr newPtr;
    newPtr=malloc(sizeof(ListNode));

if(newPtr!=0){
    newPtr->value=value;
    newPtr->nextPtr=*sPtr;
    *sPtr=newPtr;   
    }else{
    printf("%d not inserted. No memory", value);
    }
}

void insert(ListNodePtr *sPtr,int value)
{
ListNodePtr newPtr,currentPtr,previousPtr;

newPtr=malloc(sizeof(ListNode));
if(newPtr!=0){
    newPtr->value=value;
    newPtr->nextPtr=0;

currentPtr=*sPtr;
previousPtr=0;

while(currentPtr!=0&&value>currentPtr->value){
    previousPtr=currentPtr;
    currentPtr=currentPtr->nextPtr;
    }
if(previousPtr==0){
    newPtr->nextPtr=*sPtr;
    *sPtr=newPtr;
    }else{
    previousPtr->nextPtr=newPtr;
    newPtr->nextPtr=currentPtr;
    }
    }else{
    printf("%d not inserted. No memory available");
    }
}   

void printList(ListNodePtr sPtr)
{
while(sPtr!=0){
printf("%d -->",sPtr->value);
sPtr=sPtr->nextPtr;
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多