题目:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof
解题思路
- 反转链表:遍历原链表 每次新链表 = 新元素 + 上次的新链表
代码实现
public ListNode reverseList(ListNode head) {
// 每次构造的新链表
ListNode res = null;
// 遍历的
ListNode l2 = head;
// 临时的
ListNode l3 = null;
while (l2 != null) {
// 拿到当前遍历元素
l3 = new ListNode(l2.val);
// 如果为null 第一次
if (res == null) {
res = l3;
// 如果不是 那么 新元素.next = 上次构造的链表
}else {
l3.next = res;
res = l3;
}
l2 = l2.next;
}
return res;
}