剑指offer24 反转链表
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
样例
输入:1->2->3->4->5->NULL
输出:5->4->3->2->1->NULL
思路:
初始化一个新的头节点new_head,然后用尾插法把原始链表中的结点插入新的头节点。最后return new_head->next.
AcWing-35 C++ code:
/**
* 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) {
ListNode* new_head = new ListNode(-1);
ListNode* nowNode = head;
while(head){
nowNode = head;
head = head->next;
nowNode->next = new_head->next;
new_head->next = nowNode;
}
return new_head->next;
}
};
AcWing-35 python code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
new_head = ListNode(-1)
while head:
now_head = head
head = head.next
now_head.next = new_head.next
new_head.next = now_head
return new_head.next