1. Leetcode 206 反转链表

1. Leetcode 206 反转链表

206. 反转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 * 定义前,当前,临时3个节点指针
 * 当前节点不空时,先赋给临时变量指针当前的下一个节点指针
 * 再将下一个节点指针指向前一个
 * 再将前一个指向当前,最后当前节点指向临时记录的下一个节点
 * 将已经是当前节点的指针赋值给head后返回
 */
class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        struct ListNode *prev, *curr, *temp;
        prev = NULL;
        curr = head;
        while(curr != NULL)
        {
    
    
            temp = curr->next;
            curr->next = prev;
            prev = curr;
            curr = temp;
        }

        head = prev;
        return head;
        
    }
};
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        """将每个节点的后继节点指向其前驱节点即可最后返回前驱
        cur.next = pre 后继指向前驱
        prev = cur 前驱指向当前
        cur = cur.next 当前指向后继
        完成反转
        """
        cur, prev = head, None
        while cur:
            cur.next, prev, cur = prev, cur, cur.next
        return prev

猜你喜欢

转载自blog.csdn.net/weixin_39754630/article/details/116012140
今日推荐