1. 题目
2. 思路
(1) 伪头结点
- 新建一个伪头结点作为新链表的头结点,采用头插法插入原链表的结点,最后返回伪头结点的next结点即可。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
class Solution {
public ListNode ReverseList(ListNode head) {
ListNode preHead = new ListNode(0);
ListNode cur = head;
while (cur != null) {
head = head.next;
cur.next = preHead.next;
preHead.next = cur;
cur = head;
}
return preHead.next;
}
}