三指针的应用值链表反转
直接上代码,当然也给出了头插法的做法
// 链表_反转.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
//三指针,改变指针指向
ListNode* reverseList(ListNode* head) {
ListNode* n1, *n2, *n3;
n1 = NULL;
n2 = head;
if (head == NULL)
{
return NULL;
}
n3 = n2->next;
while (n2 != NULL)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if (n3 != NULL)
{
n3 = n3->next;
}
}
return n1;
}
//采用头插法构造逆序链表
ListNode* reverseList2(ListNode* head) {
ListNode * cur = head;
ListNode * newhead = nullptr;
if (head==nullptr)
{
return nullptr;
}
while (cur!= nullptr)
{
ListNode *next = cur->next;
cur->next = newhead;
newhead = cur;
cur = next;
}
return newhead;
}
};