题目描述
输入一个链表,反转链表后,输出新链表的表头。
分析
定义current指向当前遍历到的节点,pNext是当前遍历节点的下一个节点,因为需要将当前节点指向上一个节点,为了避免链表在当前节点处断开需要保存下一个节点;pPrev是当前节点的上一个节点,因为我们需要让当前节点的next指向上一个节点来实现翻转。
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode ReverseList_2(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode pReversedHead = null;
ListNode current = head;
ListNode pNext = null;
ListNode pPrev = null;
while(current != null) {
pNext = current.next;
current.next = pPrev;
if(pNext == null) {
pReversedHead = current;
}
pPrev = current;
current = pNext;
}
return pReversedHead;
}
public static void main(String[] args) {
ListNode node = new ListNode(1);
ListNode node1 = new ListNode(2);
ListNode node2 = new ListNode(3);
ListNode node3 = new ListNode(4);
ListNode node4 = new ListNode(5);
node.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = node4;
Solution s = new Solution();
node = s.ReverseList_2(node);
while(node != null) {
System.out.print(node.val + ", ");
node = node.next;
}
}
}