leetcode---Reverse Linked List---链表

来源:互联网 发布:软件无线电系统架构 编辑:程序博客网 时间:2024/04/28 02:46

Reverse a singly linked list.

/** * 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) {        if(head == NULL)            return NULL;        ListNode *p = head->next;        head->next = NULL;        while(p)        {            ListNode *tmp = p;            p = p->next;            tmp->next = head;            head = tmp;        }        return head;    }};


 

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def reverseList(self, head):        """        :type head: ListNode        :rtype: ListNode        """        if head == None:            return None        p = head.next        head.next = None        while p:            tmp = p            p = p.next            tmp.next = head            head = tmp        return head


 

0 0
原创粉丝点击