定義一個函數,輸入一個鏈表的頭節點,反轉該鏈表並輸出反轉後鏈表的頭節點。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
限制:
0 <= 節點個數 <= 5000
這裏給出兩種思路,一是雙指針頭插法建立鏈表,二是利用遞歸
雙指針
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
newHead=None;
while head!=None:
p=head.next
head.next=newHead
newHead=head
head=p
return newHead
遞歸
遞歸函數返回反轉後鏈表的頭結點,再將原鏈表的頭結點加入反轉鏈表
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if(!head||!head.next)
return head;
let ret=reverseList(head.next);
head.next.next=head; //head.next是新鏈表的尾節點
head.next=null;
return ret;
};