0
点赞
收藏
分享

微信扫一扫

(Leetcode)oj——反转链表

题目要求将一个单链表进行反转(没有前指针,单向链表)

思路1:

定义三个变量,n2是头结点,n1起初为NULL,n3为n2的下一结点

我们首先将n2的next指向n1

然后将n2赋给n1,作为新头

 然后将n3赋给n2

 接下来重复上面操作,直到n2为NULL

此时链表就变成了

具体代码如下

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head){
        struct ListNode* n1=NULL,*n2=head;
        if(head==NULL)
            return NULL;
        while(n2)
        {
           struct ListNode* n3=n2->next;
           n2->next=n1;
           n1=n2;
           n2=n3;
        }
        return n1;
}

 

其实我们仔细想想这样做法的实质其实就是在头插

就是依次将结点取出,然后头插到新链表里面

 

 

 我们不难看出,这就是在不断的取出新节点头插到新链表的循环

struct ListNode* reverseList(struct ListNode* head){
        struct ListNode* cur=head,*newhead=NULL;
        if(head==NULL)
            return NULL;
        while(cur)
        {
            struct ListNode* next=cur->next;
            cur->next=newhead;
            newhead=cur;
            cur=next;
        }
        return newhead;
}
举报

相关推荐

0 条评论