题目:输入一个链表,反转链表后,输出新链表的表头。时间限制:1秒
思路:我首先想到的是用栈存储链表,然后再依次出栈然后返回头节点。
但是,该方法太费时间,效率不高
所以,我们循环采用只遍历一次就能反转的方法
链表:1——>2——>3——>4——>5——6
我们从头开始遍历,用p.next=head把1指向2的指针反转过来
变成 1<——2 3——>4——>5——6
这样2指向3的指针就断开了,所以我们需要一个临时变量保存节点3
这样我们需要三个指针一个保存当前指针cur一个保存当前指针的前一个节点pre,一个保存当前指针的下一个节点next
ListNode pre = null;
ListNode cur = head;
ListNode next = null;
然后我们将其赋值
next = cur.next;
cur.next = pre;
再将当前指针向后移
pre = cur;
cur = next;
代码:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
ListNode cur = head;
while (cur != null) {
next = cur.next;
cur.next = pre;//将指针反转
pre = cur;
cur = next;
}
return pre;
}