LeetCode206
反转链表
题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
使用Java进行实现。在本地创建项目。
准备一个类ListNode作为节点。
这个类中跟题目中要求的节点的结构一致,还有toStrig方法,方便打印结果进行验证。
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
//链表节点的构造函数
//使用arr为参数,创建一个链表,当前的ListNode为链表头节点
public ListNode(int[] arr) {
if (arr == null || arr.length == 0) {
throw new IllegalArgumentException("arr can not be empty");
}
this.val = arr[0];
ListNode cur = this;
for (int i = 1; i < arr.length; i++) {
cur.next = new ListNode(arr[i]);
cur = cur.next;
}
}
//打印出来链表
@Override
public String toString() {
StringBuilder res = new StringBuilder();
ListNode cur = this;
while (cur != null) {
res.append(cur.val + "->");
cur = cur.next;
}
res.append("NULL");
return res.toString();
}
}
解题思路是,创建一个新的节点,有点类似于临时变量的感觉,作为反转后的链表的头节点。

再创建一个类,实现这个思路。
public class Solution206 {
/**
* 反转链表
*/
public ListNode reverseList(ListNode head) {
//指向新链表的头节点的指针
ListNode new_head = null;
while (head != null) {
//备份head->next
ListNode next = head.next;
//更新head->next
head.next = new_head;
new_head = head;
head = next;
}
return new_head;
}
}
编写测试类
public class SolutionMain {
public static void main(String[] args) {
//测试leetcode206
int[] nums = {1,2,3,4,5};
ListNode head = new ListNode(nums);
System.out.println(head);
ListNode res = (new Solution206()).reverseList(head);
System.out.println(res);
}
}
测试结果
1->2->3->4->5->NULL 5->4->3->2->1->NULL Process finished with exit code 0

浙公网安备 33010602011771号