leetcode系列206-反转链表

    技术2025-02-09  21

    【题目概要】

    206. Reverse Linked List 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?

    【思路分析】

    recursively,递归到尾节点时,以尾节点作为新的首节点,重新开始连接前面的节点iteratively,迭代时,采用三个指针的方式,一个其中两个指针同时移动,同时更换next方向,另外一个指针指向下一个移动的节点位置

    【代码示例1】

    /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ 迭代 struct ListNode* reverseList(struct ListNode* head){ if(!head) return head; struct ListNode *pfront = head; struct ListNode *pnow = head->next; struct ListNode *prear = NULL; while(pnow) { // 每次在更换pnow的方向前,需要将下一次的pnow的位置储存 prear = pnow->next; pnow->next = pfront; pfront = pnow; pnow = prear; } head->next = NULL; return pfront; } 【说明】其中真正用的思想是双指针,通过两两指针的更换next指针方向,而prear在每一次交换前,储存了 下一次的pnow指针,也就是当prear储存了null时,pnow->next= pfront

    【代码示例2】

    递归 struct ListNode* reverseList(struct ListNode* head){ // 判断条件一个是防止传入链表为空,一个是找到链表的尾节点 if(head == NULL || head->next == NULL) return head; struct ListNode *pnewhead = reverseList(head->next); head->next->next = head; head->next = NULL; return pnewhead; }
    Processed: 0.009, SQL: 9