0


刷题之:反转链表

一、函数接口

1、三指针法

接口的根据自己的需要设立,可以不返回,可以返回。

void CSList(SListNode** phead)

2、头插法

struct SListNode* reverseList(struct SListNode* phead)


二、图解思路


1、三指针法


其解题的核心是三个指针之间的相互赋值转换

2、头插法


头插法:代码的实现虽然和三指针法的大同小异,但是解题思路是完全不同的,也更加的好理解,所以要优一些

三、代码实现


1、三指针法

//三指针法
void CSList(SListNode** phead)
{
  if (*phead == NULL)
  {
      return;
  }
  else if ((*phead)->Next == NULL)
  {
      return;
  }
  SListNode* n1 = *phead;//记录当前位置
  SListNode* n2 = (*phead)->Next;//记录当前后一个地址
  SListNode* n3 = n2->Next;//记录当前后两个地址
  n1->Next = NULL;
  while (n2)
  {
      n2->Next = n1;
      n1 = n2;
      n2 = n3;
      if (n3 != NULL)
      {
      	n3 = n2->Next;
      }
  }
  *phead = n1;
}

2、头插法


//头插法
struct SListNode* reverseList(struct SListNode* phead)
{
  if (phead == NULL)
  {
      return NULL;
  }
  struct SListNode* newhead = NULL;
  struct SListNode* cur = phead;
  struct SListNode* next = cur->Next;
  while (cur)
  {
      //头插
      cur->Next = newhead;
      newhead = cur;
      //迭代
      cur = next;
      if (next != NULL)
      {
      	next = next->Next;
      }
  }
  return newhead;
}



本文转载自: https://blog.csdn.net/weixin_63246064/article/details/122792215
版权归原作者 绅士·永 所有, 如有侵权,请联系我们删除。

“刷题之:反转链表”的评论:

还没有评论