反转链表
题干
1. 直接在链表上进行反转
SListNode* reverseList2(SListNode* head){
if(head == NULL || head->next == NULL)
{
return head;
}
SListNode* n1 = NULL;
SListNode* n2 = head;
SListNode* n3 = head->next;
while(n2)
{
// 反转
n2->next = n1;
// 移动指针
n1 = n2;
n2 = n3;
if(n3)
n3 = n3->next;
}
return n1;
}
2. 头插法
当链表中的数据大于等于二的时
1地址 2地址 3地址 4地址 现在需要倒着
4地址 3地址 2地址 1地址 从最后一位开始看就相当于一直进行头插
进行头插得过程中prev始终指向的就是反转过程中的头节点,cur一直向后移动
SListNode* reverseList(SListNode* head){
if (head == NULL)
{
return NULL;
}
else if(head->next == NULL)
{
return head;
}
// 当链表中的数据大于等于二的时
// 1地址 2地址 3地址 4地址 现在需要倒着
// 4地址 3地址 2地址 1地址 从最后一位开始看就相当于一直进行头插
// 进行头插得过程
else{
SListNode* prev = head;
SListNode* cur = head->next;
// 定义一个tempnode用来存储cur指向的下一个节点
// 当cur本身为空时循环结束
while(cur)
{
SListNode* tempNode = cur->next;
cur->next = prev;
prev=cur;
cur = tempNode;
}
// 这个时候还有最后一个没有反转prev在头部 cur在尾部
head->next = NULL;
// 最后prev指向的就是反转后的头节点
return prev;
}
}