就地反转链表

#include <iostream>
using namespace std;
typedef struct ListNode
{
int data;
ListNode *next;
};
ListNode* reverseList1(ListNode *head)
{
if (head == NULL)
return head;
ListNode* dummy = new ListNode;
dummy->data = -1;
dummy->next = head;
ListNode* prev = dummy->next;
ListNode* pCur = prev->next;
while (pCur != NULL) {
prev->next = pCur->next;
pCur->next = dummy->next;
dummy->next = pCur;
pCur = prev->next;
}
return dummy->next;
}
void print(ListNode *head)
{
while (head != NULL)
{
cout << head->data;
head = head->next;
}
return;
}
int main()
{
ListNode p5{ 5, NULL };
ListNode p4{ 4, &p5 };
ListNode p3{ 3, &p4 };
ListNode p2{ 2, &p3 };
ListNode p1{ 1, &p2 };
ListNode *head = &p1;
print(head);
cout << endl;
head = reverseList1(head);
print(head);
cout << endl;
system("pause");
return 0;

}



猜你喜欢

转载自blog.csdn.net/qq_38665104/article/details/80399025