题目要求:
方法一:反转指向方向
将链表的指向方向反转,从而实现反转链表
由于单链表的尾结点的指针域为NULL,所以数字1要衔接NULL指针
通过将n1,n2,n3整体依次向右移位,实现指针域指向的改变
以此类推,重复的过程用一个while循环执行
当n2指向空,也就是n1为头节点的时候,链表的反转就终止了
注意:需要考虑当链表为空的时候,也就是head==NULL时,链表反转的返回值仍然为空
代码实现:
struct ListNode* reverseList(struct ListNode* head)
{
if(head==NULL)
{
return NULL;
}
struct ListNode* n1=NULL;
struct ListNode* n2=head;
struct ListNode* n3=n2->next;
while(n2)
{
n2->next=n1;
n1=n2;
n2=n3;
if(n3)
{
n3=n3->next;
}
}
return n1;
}
运行结果:
方法二:头插法
将旧链表的首个元素,依次头插到新链表
用cur代表头插的元素,为了保证在头插后,在旧链表能找到下一个元素,所以用next代表头插元素在旧链表中的下一个元素
第一个进行头插的元素,指针域需要指向NULL
代码实现:
//思路二:头插法
//取原链表的节点,头插到新链表
struct ListNode* reverseList(struct LisyNode* head)
{
struct ListNode* cur = head;
struct ListNode* next = cur->next;
struct ListNode* new = NULL;
while (cur)
{
cur->next = new;
new = cur;
cur = next;
}
return new;
}