题目
输入一个链表,反转链表后,输出新链表的表头。
package swordOffer;
/*
* 从头到尾遍历原链表,每遍历一个结点,将其摘下放在新链表的最前端。
* 注意链表为空和只有一个结点的情况。时间复杂度为O(n)
* */
public class ReverseList {
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static ListNode ReverseList(ListNode head) {
//如果头节点为空,则返回空
if(head == null) {
return null;
}
//如果只有一个节点,直接返回本身
if(head.next == null) {
return head;
}
ListNode current = head;//准备两个指针,一个指向现在的头部,一个用于遍历每个节点
ListNode p = current.next;
while(p != null) {
ListNode temp = p.next;//准备一个临时变量,把这个保存起来,不然会丢掉
p.next = current;
current = p;
p = temp;
}
return head;
}
public static void main(String[] args) {
ListNode node = new ListNode(5);
node.next = new ListNode(3);
node.next.next = new ListNode(4);
System.out.println(ReverseList(node).val);
}
}