题目
输入一个链表,反转链表后,输出新链表的表头。
解题思路
定义三个指针,分别指向当前遍历到的节点、他前一个节点和后一个节点。
/*
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 now = head;
ListNode next = null;
ListNode pre = null;
ListNode newhead = null;
while(now != null){
next = now.next;
if(next == null){
newhead = now;
}
now.next = pre;//修改now的指针域指向pPrev
pre = now;//将now结点复制给pPrev
now = next;
}
return newhead;
}
}