题目:输入一个链表,反转链表后,输出新链表的表头。
思路:遍历整个链表,维护两个节点pre和next,node.next每次都指向pre,然后这三个点同时向后移动。
public static Node reverseList(Node node){
Node pre = null;
Node next = null;
while(node != null){
next = node.next;
node.next = pre;
pre = node;
node = next;
}
}
完整解法:
/*
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 preNode = null;
ListNode nextNode = null;
while(head != null){
nextNode = head.next;
head.next = preNode;
preNode = head;
head = nextNode;
}
return preNode;
}
}