题目:给定单链表的头节点 head
,请反转链表,并返回反转后的链表的头节点。
示例:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
解题:用指针n1存住下一节点,另头节点指向另一指针n2,让指针n2等于头节点,头节点再等于n1,进行下一次循环。
public class ListNode {
int val;
ListNode next;
public ListNode(int Date) {
this.val = Date;
this.next = null;
}
ListNode() {
}
public ListNode getNext() {
return next;
}
@Override
public String toString() {
return val + "->" + getNext();
}
}
public static void main(String[] args) {
int[] arr = {3, 5, 7, 9};
ListNode head = new ListNode();
ListNode temp = head;
for (int i = 0; i < arr.length; i++) {
ListNode temp1 = new ListNode(arr[i]);
temp.next = temp1;
temp = temp1;
}
System.out.println(head);
System.out.print(reverseList(head));
}
public static ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode n1 = null;
ListNode n2 = null;
while (head != null) {
n1 = head.next; //暂存下面节点
head.next = n2; //头指针指n2
n2 = head; //头指针赋值给n2
head = n1; //头指针指向下一个
}
return n2;
}
输出结果: