LeetCode27.Linked List—Reverse Linked List l链表逆置

Posted hu-19941213

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode27.Linked List—Reverse Linked List l链表逆置相关的知识,希望对你有一定的参考价值。

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

思路:

重塑链表,将首结点逐个后移,移动过程中遇到的结点都依次结到链表开头。

/**
 * Definition for singly-linked list.
 * struct ListNode 
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) 
 * ;
 */
class Solution 
public:
    ListNode* reverseList(ListNode* head) 
        ListNode *p=head;        //定义指向头节点的指针
        if(p==NULL) return NULL; //使用前判断是否为空指针
        ListNode *q=p->next;     //定义第二个指针始终指向P的next
        while(p!=NULL&&q!=NULL)
        
            p->next=q->next;
            q->next=head;
            head=q;
            q=p->next;
        
        return head;
    
;

 

以上是关于LeetCode27.Linked List—Reverse Linked List l链表逆置的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode interval section

LeetCode interval section

leetcode-26-exercise_linked-list

Leetcode 142. Linked List Cycle IIJAVA语言

leetcode-easy-array-50. Intersection of Two Arrays II

LeetCode 第107题 二叉树的层次遍历II