206题目:
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
思路:使用双指针的思想,pre初始化为空,cur是头节点,依次往后移,知道pre是最后一个节点,此时cur为空。
C语言
struct ListNode* reverseList(struct ListNode* head)
{
typedef struct ListNode ListNode;
ListNode *cur=head;
ListNode *pre=NULL;
while(cur)
{
ListNode *temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
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
"""
cur=head
pre=None
while cur:
temp=cur.next
cur.next=pre
pre=cur
cur=temp
return pre
注意事项:设置空指针的时候,在C语言中是NULL,在python语言中是None
思路二:采用递归的方法
C语言
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;
struct ListNode* reversefunction(ListNode* cur,ListNode* pre)
{
if (cur==NULL)
{
return pre;
}
else
{
ListNode *temp=cur->next;
cur->next=pre;
return reversefunction(temp,cur);
}
}
struct ListNode* reverseList(struct ListNode* head)
{
return reversefunction(head,NULL);
}
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
"""
return self.reversefunction(head,None)
def reversefunction(self,cur,pre):
if cur==None:
return pre
temp=cur.next
cur.next=pre
return self.reversefunction(temp,cur)