取出原始链表的第一个节点A,然后将该节点作为新链表的头节点。对原始链表遍历一次,就完成了这个工作,所以这个算法的复杂度为O(n)。
old_head和 new_head分别表示原始链表的头节点和新链表的头节点。
public class LinkedListReverse {
static class ListNode{
int data;
ListNode next;
public ListNode(int data){
this.data = data;
}
}
public static ListNode reverse(ListNode head){
if (head == null){
return null;
}
ListNode cur = head;
ListNode oldHead = null;
ListNode newHead = null;
while(cur != null){
oldHead = cur.next;
cur.next = newHead;
newHead = cur;
cur = oldHead;
}
return newHead;
}
public static void main(String[] args) {
// 测试
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
node1.next = node2;
node2.next = node3;
ListNode head = new ListNode(0);
head = reverse(node1);
System.out.print(head.data+" "+head.next.data+" "+head.next.next.data);
}
}