头插法就地反转

#include <iostream>
using namespace std;
typedef struct ListNode
{
int data;
ListNode *next;
};
void print(ListNode *head)
{
while (head != NULL)
{
cout << head->data;
head = head->next;
}
return;
}
ListNode* reverseList1(ListNode *head)
{
if (head == NULL)
return head;
ListNode* dummy = new ListNode;
dummy->data = -1;
dummy->next = head;
ListNode *Cur = dummy->next;
ListNode *tmp = Cur->next;
while (tmp != NULL) {
Cur->next = tmp->next;
tmp->next = dummy->next;
dummy->next = tmp;
tmp = Cur->next;
//print(dummy->next);
}
Cur->next = NULL;
return dummy->next;
}
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/80402315