1
#include <iostream>
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 *p,*q;
q = p = pHead;
//1 2 3
ListNode *head = NULL;
while (q)
{
if (head == NULL)
{
head = p;
q = p->next;
head->next = NULL;
}
else{
p = q;
q = q->next;
p->next = head;
head = p;
}
}
return head;
}
};
void main(){
ListNode *head = NULL;
ListNode *q;
for (int i = 1; i<= 5;i++)
{
ListNode *p = new ListNode(i);
p->next = NULL;
if (head == NULL)
{
head = p;
q = p;
}
else{
q->next = p;
q = p;
}
}
q = head;
while (q)
{
cout<<q->val<<" ";
q= q->next;
}
cout<<endl;
class Solution s;
q = s.ReverseList(head);
while (q)
{
cout<<q->val<<" ";
q= q->next;
}
cout<<endl;
while(1);
return ;
}
2
void reverse(struct ListNode * &p) {
struct ListNode *ptr,*p1,*p2;
ptr = p;
p1 = NULL;
while (ptr != NULL) {
p2 = ptr;
ptr = ptr->next;
p2->next = p1;
p1 = p2;
}
p = p1;
}