在循环链表中使用 "static member" 还是通过迭代方式更好?
Is it better to use "static member" in circular linked list or just go by iterative way?
我为循环链表做的代码:
#include<iostream>
using namespace std;
class node
{
public:
int data;
node* next;
node():data(0),next(NULL){}
node(int x):data(x),next(NULL){}
};
void push(node** head_ref,int val);
void printlist(node* n);
int main()
{
node* head=NULL;
push(&head,14);
push(&head,24);
push(&head,67);
push(&head,77);
printlist(head);
return 0;
}
void push(node** head_ref,int val)
{
node* new_node=new node(val);
static node* temp_head=NULL;
if(*head_ref==NULL)
{
temp_head=new_node;
*head_ref=new_node;
new_node->next=*head_ref;
}
else
{
new_node->next=*head_ref;
temp_head->next=new_node;
*head_ref=new_node;
}
}
void printlist(node* n)
{
node* head_ref=n;
while(n!=NULL)
{
cout<<n->data<<" ";
if(n->next!=head_ref){n=n->next;}
else if (n->next==head_ref){break;}
}
}
我正在尝试为循环链表编写代码。
我在 void push() 中使用了 static node* 是好方法还是采用迭代方法
通过使用 while-for 循环?
好的,首先关于静态变量,保留最后一个节点是一个很好的 hack(我认为您在开始实现代码时打算这样做)。但快速说明一下,在这种情况下,您的循环链表将被反转,因为根据链表的思想,您应该将节点添加到列表的末尾而不是前面(您就是这样做的)。如果您告诉我这是一个反向链表的代码,我肯定会认为代码是好的。
这是您的推送功能的伪代码
node* new_node=new node(val);
static node* temp_head=nullptr;
if(*head_ref==nullptr)
{
temp_head=new_node;
*head_ref=new_node;
new_node->next=*head_ref;
}
else
{
temp_head->next = new_node;
temp_head = temp_head->next;
temp_head->next = *head_ref;
}
但是请看一下循环链表的其他一些实现,因为这个不能被标记为已批准。您应该有一个 class CircularLinkedList,它将执行所有操作,如推送或打印。
我为循环链表做的代码:
#include<iostream>
using namespace std;
class node
{
public:
int data;
node* next;
node():data(0),next(NULL){}
node(int x):data(x),next(NULL){}
};
void push(node** head_ref,int val);
void printlist(node* n);
int main()
{
node* head=NULL;
push(&head,14);
push(&head,24);
push(&head,67);
push(&head,77);
printlist(head);
return 0;
}
void push(node** head_ref,int val)
{
node* new_node=new node(val);
static node* temp_head=NULL;
if(*head_ref==NULL)
{
temp_head=new_node;
*head_ref=new_node;
new_node->next=*head_ref;
}
else
{
new_node->next=*head_ref;
temp_head->next=new_node;
*head_ref=new_node;
}
}
void printlist(node* n)
{
node* head_ref=n;
while(n!=NULL)
{
cout<<n->data<<" ";
if(n->next!=head_ref){n=n->next;}
else if (n->next==head_ref){break;}
}
}
我正在尝试为循环链表编写代码。 我在 void push() 中使用了 static node* 是好方法还是采用迭代方法 通过使用 while-for 循环?
好的,首先关于静态变量,保留最后一个节点是一个很好的 hack(我认为您在开始实现代码时打算这样做)。但快速说明一下,在这种情况下,您的循环链表将被反转,因为根据链表的思想,您应该将节点添加到列表的末尾而不是前面(您就是这样做的)。如果您告诉我这是一个反向链表的代码,我肯定会认为代码是好的。 这是您的推送功能的伪代码
node* new_node=new node(val);
static node* temp_head=nullptr;
if(*head_ref==nullptr)
{
temp_head=new_node;
*head_ref=new_node;
new_node->next=*head_ref;
}
else
{
temp_head->next = new_node;
temp_head = temp_head->next;
temp_head->next = *head_ref;
}
但是请看一下循环链表的其他一些实现,因为这个不能被标记为已批准。您应该有一个 class CircularLinkedList,它将执行所有操作,如推送或打印。