输入一个链表,反转链表后,输出新链表的表头。
#include <iostream>
#include <cstdlib>
using namespace std
;
struct ListNode
{
int val
;
struct ListNode
*next
;
ListNode(int x
) :
val(x
), next(NULL) {
}
};
class Solution{
public:
ListNode
*ReverseList(ListNode
* pHead
){
if(pHead
== NULL||pHead
->next
== NULL)
return pHead
;
ListNode
*newHead
,*p1
,*p2
;
newHead
= NULL;
p1
= pHead
;
p2
= NULL;
while(p1
!=NULL)
{
p2
= p1
->next
;
p1
->next
= newHead
;
newHead
= p1
;
p1
= p2
;
}
return newHead
;
}
};
int main()
{
Solution solve
;
ListNode
*s
,*L
,*p
;
L
= (ListNode
*)malloc(sizeof(ListNode
));
L
->next
= NULL;
for(int i
= 0;i
<9;i
++)
{
s
= (ListNode
*)malloc(sizeof(ListNode
));
s
->val
= i
;
s
->next
= L
->next
;
L
->next
= s
;
}
p
= L
->next
;
while(p
!=NULL)
{
cout
<<p
->val
<<" ";
p
= p
->next
;
}
cout
<<endl
;
p
= solve
.ReverseList(L
->next
);
while(p
)
{
cout
<<p
->val
<<" ";
p
= p
->next
;
}
p
= L
->next
;
while(p
!=NULL)
{
free(L
);
L
= p
;
p
= L
->next
;
}
free(L
);
return 0;
}
结果
转载请注明原文地址:https://tech.qufami.com/read-22643.html