题目描述
输入一个链表,反转链表后,输出新链表的表头。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
}
}
解题思路
- 注意避免头结点为空的情况,反转后链表出现断裂
- 所以我们需要先用next节点把节点保存下来,然后把之前的next节点指向前一个节点
- 让pre,head,next依次向后移动一个节点,继续下一次的指针反转
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
if (head == null){
return null;
}
while (head!=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
}