原题链接:https://leetcode.com/problems/reverse-linked-list/
题目:
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
思路:
头插法建立链表
算法:
[java] view
plain copy
- public ListNode reverseList(ListNode head) {
- ListNode p = head, q, t;
- if (p == null)
- return head;
- q = p.next;
- while (q != null) {
- t = q.next;//保存当前要处理结点后面的一个结点
- q.next = p;
- p = q; //p是新链表头结点
- q = t;
- }
- head.next = null;//原头结点变成尾节点
- head = p;
- return head;
- }
时间: 2024-12-10 21:41:43