# 面试算法之链表操作集锦

template <typename Type>
struct ListNode{
Type data;
ListNode *next;
};

/**
* Create a list, without head node
*/
template <typename Type>
ListNode<Type> *CreatList(Type *data, int len)
{
if(data == NULL || len <= 0)
return NULL;

ListNode<Type> *head, *last;

head = new ListNode<Type>;
last = head;

for (int i = 0; i < len; ++i)
{
last->next = new ListNode<Type>;
last->next->data = data[i];
last = last->next;
}

last->next = NULL;

last = head;
head = head->next;

delete last;

return head;
}

#### 1.单链表的逆序打印

/**
* reversely print the list
* method 1: use the stack
*/
template <typename Type>
void ReversePrintList_1(const ListNode<Type> *head)
{
if(head == NULL)
return;

stack<Type> nodeStack;
while (head)
{
nodeStack.push(head->data);
head = head->next;
}

while(!nodeStack.empty())
{
cout<<nodeStack.top()<<" ";
nodeStack.pop();
}
cout<<endl;
}


/**
* reversely print the list
* method 2: recursively
*/
template <typename Type>
void ReversePrintList_2(const ListNode<Type> *head)
{
if(head == NULL)
return;

ReversePrintList_2(head->next);
cout<<head->data<<" ";
}

• 4
点赞
• 4
收藏
觉得还不错? 一键收藏
• 3
评论
03-20 5939
01-27 72
04-21 6万+
08-28 459
10-11 233
08-01 463
04-02 221
06-07 379
08-30 738
03-13 460
05-08 493
03-02 1635
07-04 169

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。