题目:实现单向链表的反转。
以下是我的代码。
思路一:新建链表,利用临时指针的偏移完成新链表的穿插。
#include <iostream>
using std::cout;
using std::endl;
struct node
{
int val;
node *next;
};
void Reverse(node * &root)
{
node *cpy,*lst,*cur,*nxt,*head;
lst = root;
cur = root->next; //指向链表的下一个节点
head = root;
head->next = NULL;
while(cur != NULL)
{
nxt = cur->next;
cpy = lst;
lst = cur;
cur = nxt;
lst->next = cpy;
/*cpy = cur;
cur = cur->next; //这是我自己的算法,就是新建一个链表,把原来的链表从头查到新链表的末尾,就连表往后移,新链表指针往前走
cpy->next = head->next;
head->next = cpy;*/
}
//root = head; //这是我的算法最后的节点
root = lst;
}
void Show(node *root)
{
node *cur = root;
while(cur != NULL)
{
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int main(void)
{
node *head,*tmp,*cur;
head = new node;
head->val = 2010;
cur = head;
for(int i = 0;i < 10; i++)
{
tmp = new node;
tmp->val = i;
tmp->next = NULL;
cur->next = tmp;
cur = tmp;
}
Show(head);
Reverse(head);
Show(head);
return 0;
}
思路二:利用栈的思想。将链表设计成栈,然后创建新的链表将Pop的结果穿插成新的链表。
代码略。