LeetCode——两种方法实现反转链表(逆置链表)

**反转链表**:
实现链表的逆置
最终将头节点转为尾节点,尾结点转为头节点
/*
struct ListNode{
    int val;
    struct ListNode *next;
}
*/

方法1:
n1,n2反转,n3迭代
struct ListNode *reverseList(struct ListNode* head)
{
    
    
//如果头节点为空或者只存在一个头节点,则直接返回头节点指针
      if(head==NULL||head->next==NULL)
     {
    
    
      return head;
     }
     //定义三个节点指针
   struct ListNode *n1=NULL,*n2=NULL,*n3=NULL;
   n2=head;
   n3=head->next;
  //n1指向为空,n2指向头节点,n3指向头节点的下一个节点
   
   while(n2!=NULL)
   {
    
    
   //当n2不为空,进入循环
   //n2指向n1,之后n2赋值给n1,n3赋值给n2,
      n2->next=n1;
      n1=n2;
      n2=n3;
      
       if(n3)
      {
    
    
        n3=n3->next;
        //当n3为空时,不能进行n3=n3->next 操作
        //因为空指针或者野指针都不能进行解引用操作
        
      }
  }

      return n1;
      //返回新的头节点

}

在这里插入图片描述



方法2:
将原链表节点依次头插到新链表中,达到链表反转的效果

 struct SListNode *reverseList(struct SListNode *head)
{
    
    
    if(head==NULL||head->next=NULL)
       {
    
    
          return head;
       }
    struct SListNode *newhead=NULL;
    //建立一个新链表,新链表头结点指针指向为空
    struct SListNode *cur=head;
    //定义一个结点指针指向原链表头结点
      while(cur)
   {
    
    
      struct SListNode *next=cur->next;
      //定义一个结点next用来更新cur指针
      cur->next=newhead;//头插插入新链表
      newhead=cur;
      cur=next;

   }
   return newhead;
   //返回新链表头结点
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/cfk17829572643/article/details/113714881