【剑指offer】24.反转链表
程序员文章站
2022-03-11 17:24:30
...
题目描述
输入一个链表,反转链表后,输出新链表的表头。
思路
将指针反转
class Node{
public int val;
public Node next;
public Node(int data){
this.val = data;
}
}
public class Offer24_ReverseList {
public static Node reverseList(Node head){
Node pre = null;
Node next = null;
while(head!= null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static void printLinkedList(Node head){
System.out.print("Lined List:");
while(head != null){
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
printLinkedList(head);
head = reverseList(head);
printLinkedList(head);
}
}
上一篇: 剑指offer 24. 反转链表
下一篇: 剑指 Offer 24. 反转链表