目录
1、题目描述:
2、解题思路及方法:
2.1 法一:三指针法
2.2 法二:单链表头插法
3、总结:
题目链接:206. 反转链表 - 力扣(LeetCode) (leetcode-cn.com)
1、题目描述:
2、解题思路及方法:
2.1 法一:三指针法
struct ListNode* reverseList(struct ListNode* head){
//当链表为NULL时,直接返回头指针
if (NULL == head)
{
return head;
}
struct ListNode* n1 = NULL;
struct ListNode* n2 = head;
struct ListNode* n3 = head->next;
while (n2 != NULL)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if (n3 != NULL)
{
n3 = n3->next;
}
//当n3为NULL时,不再指向下一个节点
}
return n1;
}
2.2 法二:单链表头插法
struct ListNode* reverseList(struct ListNode* head){
//当链表为NULL时,返回头指针
if (NULL == head)
{
return head;
}
struct ListNode* cur = head;
struct ListNode* next = head->next;
struct ListNode* newhead = NULL;
while (cur)
{
cur->next = newhead;
newhead = cur;
cur = next;
if (NULL != next)
{
next = next->next;
}
}
return newhead;
}
2.1 法一:三指针法
struct ListNode* reverseList(struct ListNode* head){
//当链表为NULL时,直接返回头指针
if (NULL == head)
{
return head;
}
struct ListNode* n1 = NULL;
struct ListNode* n2 = head;
struct ListNode* n3 = head->next;
while (n2 != NULL)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if (n3 != NULL)
{
n3 = n3->next;
}
//当n3为NULL时,不再指向下一个节点
}
return n1;
}
2.2 法二:单链表头插法
struct ListNode* reverseList(struct ListNode* head){
//当链表为NULL时,返回头指针
if (NULL == head)
{
return head;
}
struct ListNode* cur = head;
struct ListNode* next = head->next;
struct ListNode* newhead = NULL;
while (cur)
{
cur->next = newhead;
newhead = cur;
cur = next;
if (NULL != next)
{
next = next->next;
}
}
return newhead;
}
struct ListNode* reverseList(struct ListNode* head){
//当链表为NULL时,直接返回头指针
if (NULL == head)
{
return head;
}
struct ListNode* n1 = NULL;
struct ListNode* n2 = head;
struct ListNode* n3 = head->next;
while (n2 != NULL)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if (n3 != NULL)
{
n3 = n3->next;
}
//当n3为NULL时,不再指向下一个节点
}
return n1;
}
struct ListNode* reverseList(struct ListNode* head){ //当链表为NULL时,返回头指针 if (NULL == head) { return head; } struct ListNode* cur = head; struct ListNode* next = head->next; struct ListNode* newhead = NULL; while (cur) { cur->next = newhead; newhead = cur; cur = next; if (NULL != next) { next = next->next; } } return newhead; }
3、总结:
这两种方法的本质相同,都是单链表的一些基本操作。在做题时,要多多考虑特殊情况:传来的链表为NULL,对野指针的访问等等。
这两种方法的本质相同,都是单链表的一些基本操作。在做题时,要多多考虑特殊情况:传来的链表为NULL,对野指针的访问等等。



