实习面试了三次,两次问道这个题目,有必要整理一下了。
Reversea singly linked list.
#方法一:
使用迭代的方法,算法时间复杂度是O(n),
空间复杂度为O(1)
/**
* 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 || head -> next == NULL)
return head;
else
{
ListNode* p = head;
ListNode* t = NULL;
ListNode* h = NULL;
while(p != NULL)
{
h = p -> next;
p -> next = t;
t = p;
p = h;
}
head = t;
}
return head;
}
};
#方法二
使用递归
/**
* 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 || head -> next == NULL)
return head;
else
{
ListNode* newhead = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL
}
}
};
PYTHON:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
p = None
c = head
while c:
temp = c.next
c.next = p
p = c
c = temp
return p