剑指OFFER笔记_24_反转链表_JAVA实现
题目:反转链表
- 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
解题思路
- 此题需要考虑到一个关键点:当一个节点的next被修改后,如何找到该节点的原next节点?我采取了提前保存的方法。
- 起始的head节点如何处理?应该让这个节点指向null,也就是作为尾节点。
- 如何判断到了尾节点?当这个节点的next==null的时候,证明该节点就是链表的最后一个节点,可以将其返回。
代码
ListNode结构代码
package q24;
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
this.val = x;
this.next = null;
}
public static ListNode createLink(int[] arr)
{
if (arr == null || arr.length == 0)
{
return null;
}
ListNode head = new ListNode(arr[0]);
ListNode pNode = head;
for (int i = 1; i < arr.length; i++)
{
ListNode temp = new ListNode(arr[i]);
pNode.next = temp;
pNode = pNode.next;
}
return head;
}
public static void outputLink(ListNode head)
{
ListNode pNode = head;
while (pNode != null)
{
System.out.print(pNode.val + " ");
pNode = pNode.next;
}
System.out.println();
}
}
函数主体部分代码
package q24;
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null)
{
return null;
}
//指向三个节点
ListNode preNode = null;
ListNode curNode = head;
ListNode nextNode = curNode.next;
//若只有一个节点
if (nextNode == null) {
curNode.next = null;
return curNode;
}
//若有多个节点
while (nextNode != null)
{
curNode.next = preNode;
preNode = curNode;
curNode = nextNode;
nextNode = nextNode.next;
}
curNode.next = preNode;
return curNode;
}
}
测试部分代码
package q24;
public class TestApp {
public static void main(String[] args) {
Solution s = new Solution();
//空结点的情况
int[] nodeArr1 = {};
ListNode head = ListNode.createLink(nodeArr1);
ListNode.outputLink(head);
ListNode head2 = s.reverseList(head);
ListNode.outputLink(head2);
//一个节点的情况
int[] nodeArr2 = {1};
head = ListNode.createLink(nodeArr2);
ListNode.outputLink(head);
head2 = s.reverseList(head);
ListNode.outputLink(head2);
//多个节点的情况
int[] nodeArr3 = {1,2,3,4,5,6,7};
head = ListNode.createLink(nodeArr3);
ListNode.outputLink(head);
head2 = s.reverseList(head);
ListNode.outputLink(head2);
}
}
运行结果截图
LeetCode运行截图