题目:反转一个单链表
链表结构如下:
struct ListNode
{
int val;
struct ListNode *next;
};
方法一:
算法思想:用三个指针 n1 , n2 , n3
起初,n1指向头head,n2指向第二个结点,n3指向第三个结点;先让n1的next指向空,循环判断n2是否为空,让n2头插到n1后面(n2->next = n1),再挪动指针n1,n2,n3。
代码如下:
struct ListNode* reverseList(struct ListNode* head)
{
if (head == NULL || head->next == NULL)
return head;
struct ListNode* n1, *n2, *n3;
n1 = head;
n2 = n1->next;
n3 = n2->next;
n1->next = NULL;
while (n2)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if (n3 != NULL)
n3 = n3->next;
}
return n1;
};
方法二:
新创建一个结点newHead = NULL,拿下来结点进行头插,直到最后一个结点
struct ListNode* reverseList(struct ListNode* head)
{
struct ListNode* cur = head;
struct ListNode* newHead = NULL;
while (cur)
{
struct ListNode* next = cur->next;
cur->next = newHead;
newHead = cur;
cur = next;
}
return newHead;
}