题目描述
输入一个链表,反转链表后,输出新链表的表头。
实现代码如下:
public class ListNode {
int val;
ListNode next = nill
ListNode(int val) {
this.val = val;
}
}
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null){//当链表为空或者只有一个头节点时
return haed;
}
ListNode pre = null;// 当前节点的前一个节点
ListNode cur = head; //当前节点
ListNode post = null;// 当前节点的下一个节点
while(cur != null){
post = cur.next;// 记录当前节点的下一个节点位置
cur.next = pre;// 让当前节点指向前一个节点位置,完成反转
pre = cur; //pre 往右走
cur = post;// 当前节点往右继续走
}
return pre;
}