定義乙個函式,輸入乙個鍊錶的頭結點,反轉該鍊錶並輸出反轉後鍊錶的頭結點。
樣例
輸入: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
* };
*/class
solution
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
劍指Offer 24 反轉鍊錶
定義乙個函式,輸入乙個鍊錶的頭節點,反轉該鍊錶並輸出反轉後鍊錶的頭節點。例 輸入 1 2 3 4 5 none 輸出 5 4 3 2 1 none 雙指標遍歷鍊錶,將當前節點的next設為前乙個節點。注意儲存當前節點的next來遍歷。時間複雜度 o n 空間複雜度 o 1 def reverse l...
劍指offer24 反轉鍊錶
定義乙個函式,輸入乙個鍊錶的頭結點,反轉該鍊錶並輸出轉換後的頭結點。首先,從題目中可得知為單鏈表結構,只有指向下乙個元素的指標。而要完成整個鍊錶的反轉則需要將所有next指標進行反轉。定義3個指標,分別指向當前遍歷的節點 它的前乙個節點以及後乙個節點。pnode ppre pre pnode phe...
劍指offer24 反轉鍊錶
題目 定義乙個函式,輸入乙個鍊錶的頭節點,反轉該鍊錶並輸出反轉後鍊錶的頭節點。鍊錶定義如下 struct listnode 思路 首先將pcur和pnext指向第乙個資料結點,phead的指標域置為null,再將pnext指向pcur指向結點的下乙個結點,pcur的指標域指向phead指向的結點,p...