一、题目描述
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
二、代码
主要是和我刚刚做完的反转链表都可以用同一个思路来解释,就直接用了刚才的思路,发现确实可以
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun reverseList(head: ListNode?): ListNode? {
val stack = Stack<Int> ()
var p = head
while(p != null){
stack.push(p!!.`val`)
p = p!!.next
}
var count = 0
p = head
while(count < stack.size){
p!!.`val` = stack.pop()
p = p.next
}
return head
}
}
来自leetcode超过100%的代码
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun reverseList(head: ListNode?): ListNode? {
var p = head
var q: ListNode? = null
while (p != null) {
val count = p.next
p.next = q
q = p
p = count
}
return q
}
}