题目描述
输入一个链表,反转链表后,输出新链表的表头。例如:
输入:
{1,2,3}
返回:
{3,2,1}
思路
双指针,用pre指针记录当前结点的前一个结点地址,用next记录当前结点的下一个结点地址,遍历链表,每次都令当前结点指向pre,并记录链表,防止断链,当前结点指向null时,返回pre即为新链表的表头。
Java实现
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
//pre记录当前结点的前一个结点地址
ListNode pre = null;
//next记录当前结点的下一个结点地址
ListNode next = null;
while (head != null) {
//next记录head的下一个结点,防止断链
next = head.next;
//指针逆置,指向前一个结点
head.next = pre;
//pre后移
pre = head;
//head后移
head = next;
}
//head结点指向null,pre即为表头
return pre;
}
}