题目描述
输入一个链表,反转链表后,输出新链表的表头。
思路
用一个指针来保存链表倒序,遍历一次链表,每获取一个节点就把该节点加到新链表的表头,再让指针指向表头,如此反复直到遍历结束即可。
Code
- Python
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
p = pHead
q = None
while p is not None:
n = p
p = p.next
n.next = q
q = n
return q
- JavaScript
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function ReverseList(pHead)
{
let p = pHead
let q = null
while(p) {
let n = p
p = p.next
n.next = q
q = n
}
return q
}
网友评论