2016-11-21 200 views
-3

目前正在对我的项目,洗牌是最后一个功能我必须写,但我很困惑,我不知道洗牌链表栈

怎么可以在这里谁能帮助我?不管怎么说,还是要谢谢你 !

所以这里是我的类

// 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"); 
} 

}; 

任何帮助表示赞赏!

+1

为什么要洗牌堆栈?一个堆栈的要点是保持FILO的排序,洗牌失败的目的。 – lcs

+1

[Randomly shuffling a linked list]的可能重复(http://stackoverflow.com/questions/23094055/randomly-shuffling-a-linked-list) –

+0

请更具体地了解实际需求。另外,你为什么要重新实现而不是使用容易成为该语言一部分的概念?最后,你的实现仍然需要工作(例如你的pop方法在打印“Empty Stack”之后仍然会崩溃) –

回答

0

您可以创建一个包含所有节点地址的向量,称之为V,并创建一组索引从1到N(N是节点数),称之为I.创建一个空堆栈S. Now:(psuedocode)

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])