把链表相邻元素反转
#include "iostream"
using namespace std;
struct ListNode
{
int mVlaue;
ListNode* pNext;
};
ListNode* reverseList(ListNode* head)
{
if (head==NULL || head->pNext==NULL)
return head;
ListNode *pre = head,*cur = head->pNext,*next = NULL;
while (cur!=NULL && cur->pNext!=NULL)
{
next = cur->pNext->pNext;
pre->pNext = cur->pNext;
cur->pNext->pNext = cur;
cur->pNext=next;
pre=cur;
cur=next;
}
return head;
}
ListNode* creatList()
{
ListNode* head = NULL;
ListNode* CurNode = head;
for (int i=1;i<=5;i++)
{
ListNode* TempNode = new ListNode;
TempNode->mVlaue = i;
TempNode->pNext = NULL;
if (head == NULL)
{
CurNode = TempNode;
head = TempNode;
}
else
{
CurNode->pNext = TempNode;
CurNode = TempNode;
}
}
return head;
}
void printList(ListNode* head)
{
while (head)
{
if (head->pNext)
cout<<head->mVlaue<<"->";
else
cout<<head->mVlaue;
head= head->pNext;
}
cout<<endl;
}
int main()
{
ListNode* head = NULL;
head = creatList();
printList(head);
ListNode* NewHead = reverseList(head);
printList(NewHead);
system("pause");
return 0;
}