【问题标题】:shuffling a linked list stack洗牌链表堆栈
【发布时间】:2016-11-21 18:41:59
【问题描述】:

目前正在处理我的项目,洗牌是我必须编写的最后一个函数,但我很困惑,我不知道如何

这里有人可以帮助我吗?还是谢谢!

这是我的课

//   Creating a NODE Structure
struct node
{
    int data;
    struct node *next;

};


// Creating a class STACK
class tumpukan
{
    struct node *top;
    public:
    tumpukan() // constructure
    {
        top=NULL;
    }
void push(int x)
{
    struct node *ptr;
    ptr=new node;
    ptr->data=x;
    ptr->next=NULL;
    if(top!=NULL)
    ptr->next=top;
    top=ptr;
}



int pop()
{
struct node *temp;
    if(top==NULL)
        {
            printf("Tumpukan Kosong \n");
        }
temp=top;
top=top->next;
return temp->data;
delete temp;
}



void show()
{
    struct node *ptr1=top;
    printf("isi tumpukan  : \n");
    while(ptr1!=NULL)
    {
    cout<<ptr1->data<<" ->";
    ptr1=ptr1->next;
    }
    printf("NULL \n");
}

};

感谢任何帮助!

【问题讨论】:

  • 为什么要洗牌?堆栈的目的是保持 FILO 排序,洗牌会破坏这个目的。
  • 请根据实际要求更具体。此外,您为什么要从头开始重新实现,而不是使用很容易成为语言一部分的概念?最后,您的实现仍然需要工作(例如,您的 pop 方法在打印“Empty Stack”后仍然会崩溃)

标签: c++ linked-list shuffle


【解决方案1】:

你可以制作一个包含所有节点地址的向量,称为 V,并制作一组从 1 到 N(N 是节点数)的索引,称为 I。创建一个空堆栈 S。 现在:(伪代码)

for i in range 1 to V.size():
   index=I.pick_at_rand() // you can easily find these sort of functions
   I.delete(index)
   if(S.top!=NULL):
      V[i].next=S.top
      S.push(V[index])
   else:
      S.push(V[index])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-02
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多