“链表基本问题。”
题干
给你单链表的头节点 ,请你反转链表,并返回反转后的链表。
示例
示例 1:
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
示例 2:
输入:head = [] 输出:[]
链表的数据格式定义:
// Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
复制下面的代码到ide中,并补全函数:
class Solution {
public ListNode reverseList(ListNode head) {
}
}
题解
数据结构基本问题,较容易,但是可以考察面试者基本编码素质和心理素质:
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) { return null; }
if (head.next == null) { return head; }
ListNode p, q, tmp;
p = head;
q = head.next;
p.next = null;
while (q != null) {
tmp = q.next;
q.next = p;
p = q;
q = tmp;
}
return p;
}
}
Be the first person to leave a comment!