四种语言刷算法之反转链表

力扣206. 反转链表

1、C

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

struct ListNode* reverseList(struct ListNode* head){
    if(head==NULL||head->next==NULL)return head;
    struct ListNode* p = NULL;
    struct ListNode* q = head;
    while(q!=NULL){
        struct ListNode* r = q->next;
        q->next = p;
        p = q;
        q = r;
    }
    return p;
}

2、C++

/**
 * 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) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==nullptr||head->next==nullptr)return head;
        ListNode* p = nullptr;
        ListNode* q = head;
        while(q!=nullptr){
            ListNode* r = q->next;
            q->next = p;
            p = q;
            q = r;
        }

        return p;
    }
};

3、JAVA

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null)return head;
        ListNode p = null;
        ListNode q = head;
        while(q!=null){
            ListNode r = q.next;
            q.next = p;
            p = q;
            q = r;
        }
        return p;
    }
}

4、Python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None or head.next is None:
            return head
        p = None
        q = head
        while(q is not None):
            r = q.next
            q.next = p
            p = q
            q = r
        return p
posted @ 2023-03-09 09:16  菜鸟冲冲冲  阅读(18)  评论(0)    收藏  举报