题目
输入一个链表,反转链表后,输出新链表的表头。
示例1
- 输入
{1,2,3}
- 返回值
{3,2,1}
说明:本题目包含复杂数据结构ListNode
Java
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) return null;
ListNode pre = null;
ListNode next = null;
while(head != null) {
next = head.next;
//断开下结点与当前结点的连接, 与前一结点连接
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}