输入一个链表,反转链表后,输出新链表的表头。
方法一: 逐个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) {
return null;
}
//只有一个节点
if (head.next == null) {
return head;
}
//前节点
ListNode preNode = null;
//现节点
ListNode curNode = head;
//后节点
ListNode nextNode = null;
while(curNode !=null) {
nextNode = curNode.next;
//到末尾
if (nextNode == null) {
//重置头节点
head = curNode;
}
//反转next指针
curNode.next = preNode;
//注意下面这两步不可以调换顺序
//pre指针指向cur
preNode = curNode;
//将cur指针指向next
curNode = nextNode;
}
return head;
}
}
方法二: 先对原链表做头删操作,再对新链表做头插
/*
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) {
return null;
}
//只有一个节点
if (head.next == null) {
return head;
}
//新头节点
ListNode newHead = null;
ListNode curNode = null;
//是否到尾部
while (head != null) {
//让curNode指针指向头指针head,两指针指向保持相同
curNode = head;
//头删操作
head = head.next;
//让curNode指针的next指向新链表的头指针newHead,完成结点的链接
curNode.next = newHead;
newHead = curNode;
}
return newHead;
}
}