时间限制:1000MS 代码长度限制:10KB
提交次数:0 通过次数:0
题型: 填空题 语言: 不限定
Description
一道经典的题目 给定一个单链表的头结点L,长度为n,反转该链表后,返回新链表的表头。 要求:空间复杂度 O(1) ,时间复杂度 O(n)。 如当输入链表{1,2,3}时, 经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
#include <iostream>//C++
using namespace std;
struct LNode
{
int data;
LNode * next;
};
void createList(LNode * &L,int n)
{
/**< 尾插法创建单链表 */
LNode *r, *p;
r=L=new LNode;/**< 创建头结点 */
L->next=NULL;
for(int i=1; i<=n; i++)
{
p=new LNode;
cin>>p->data;
p->next=NULL;
r->next=p;
r=p;
}
}
void trv(LNode * L)
{
/**< 一个简单的链表遍历函数,供编程过程中测试使用 */
L=L->next;
while(L)
{
cout<<L->data<<' ';
L=L->next;
}
}
void reverseList(LNode * &L)
{
LNode *pre = NULL;/**< 用三个指针分别表示前驱,当前,后继 */
LNode *cur = L->next;/**< 当前是第一个节点a1 */
LNode *nex = NULL; /**<思考如何用这三个指针实现翻转,另外,三个指针也要同步后移 */
while (cur)
{
_______________________
}
L->next=pre;
}
int main()
{
int n;
LNode *L;
cin>>n;
createList(L,n);
reverseList(L);
trv(L);
return 0;
}
输入格式
第一行一个整数n,代表链表长度。 第二行n个整数。
输出格式
输出逆置后的单链表。
输入样例
5 1 2 3 4 5
输出样例
5 4 3 2 1
作者
30002692
Version:
2
#include <iostream>//C++
using namespace std;
struct LNode
{
int data;
LNode * next;
};
void createList(LNode * &L,int n)
{
/**< 尾插法创建单链表 */
LNode *r, *p;
r=L=new LNode;/**< 创建头结点 */
L->next=NULL;
for(int i=1; i<=n; i++)
{
p=new LNode;
cin>>p->data;
p->next=NULL;
r->next=p;
r=p;
}
}
void trv(LNode * L)
{
/**< 一个简单的链表遍历函数,供编程过程中测试使用 */
L=L->next;
while(L)
{
cout<<L->data<<' ';
L=L->next;
}
}
void reverseList(LNode * &L)
{
LNode *pre = NULL;/**< 用三个指针分别表示前驱,当前,后继 */
LNode *cur = L->next;/**< 当前是第一个节点a1 */
LNode *nex = NULL; /**<思考如何用这三个指针实现翻转,另外,三个指针也要同步后移 */
while (cur)
{
pre = cur;
cur = cur->next;
pre->next = nex;
nex = pre;
}
L->next=pre;
}
int main()
{
int n;
LNode *L;
cin>>n;
createList(L,n);
reverseList(L);
trv(L);
return 0;
}