题目
输入一个链表,反转链表后,输出新链表的表头。
分析:
(1)边界条件: 头节点为空或者头节点的下一个节点为空时,返回head
(2)使用三个辅助指针节点,pre, cur , next
(3) 遍历链表时, 先保存cur节点的下一个节点信息;
再使cur.next指向pre
再使pre = cur
再使cur = next
直到cur为空时,遍历结束。
此时,pre节点即为头节点。
代码实现
/*
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 || head.next == null){
return head;
}
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
注:反转部分链表类似。