链表翻转

ListNode* ReverseList(ListNode* pHead)
{
if (pHead == NULL)
{
return NULL;
}

ListNode pHeadNew(0);
pHeadNew.next = pHead;

ListNode* curNode = pHead;
ListNode* nextNode = pHead->next;
while (nextNode != NULL)
{
curNode->next = nextNode->next;
nextNode->next = pHeadNew.next;
pHeadNew.next = nextNode;
nextNode = curNode->next;
}

return pHeadNew.next;
}

struct ListNode
{
int val;
struct ListNode *next;
ListNode(int x):val(x), next(NULL)
{
}
};

class Solution {
public:
ListNode* ReverseList(ListNode* head)
{
ListNode* pre = NULL;
ListNode* next = NULL;
while ( head != NULL)
{
next = head->next;
head->next = pre;
pre = head;
head = next;
}

return pre;
}
};


int main()
{
int arr[] = { 8,2, 1 , 2, 6, 10 };
int n = sizeof(arr) / sizeof(int);
/*
// 冒泡排序
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j ++)
{
if (arr[j] > arr[j+1])
{
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}*/

/*
// 选择排序
for (int i = 0; i < n - 1; i++)
{
int min = i;
for (int j = i + 1; j < n; j++)
{
if (arr[min] > arr[j])
{
min = j;
}
}

int tmp = arr[i];
arr[i] = arr[min];
arr[min] = tmp;

}*/


struct ListNode a1(1);
struct ListNode a2(3);
struct ListNode a3(2);
struct ListNode a4(8);

ListNode* pHead = &a1;
a1.next = &a2;
a2.next = &a3;
a3.next = &a4;

ListNode* tmp = pHead;
while (tmp != NULL)
{
cout << tmp->val;
tmp = tmp->next;
}
cout << endl;

Solution sss;
pHead = sss.ReverseList(pHead);

tmp = pHead;
while (tmp != NULL)
{
cout << tmp->val;
tmp = tmp->next;
}

cout << endl;
return 0;
}

青青园中葵,朝露待日晞。 阳春布德泽,万物生光辉。 常恐秋节至,焜黄华叶衰。 百川东到海,何时复西归? 少壮不努力,老大徒伤悲!
原文地址:https://www.cnblogs.com/weiyouqing/p/14474021.html