- 打卡算法 反转算法 2021/5/28
描述
输入一个链表,反转链表后,输出新链表的表头。
示例1
输入:
{1,2,3}
返回值:
{3,2,1}
解题思路
- 判断是否为null或者next为null,是return,否进去2。
- 设置当前指针为头指针,前指针pre和后指针next为null。
- 后指针next指向下一位。
- 当前指针指向前指针。
- 前指针指向当前指针。
- 当前指针指向next。
解题代码
public static ListNode ReverseList(ListNode node){
if(node==null||node.next==null)
return node;
ListNode head = node;
ListNode pre = null;
ListNode next = null;
while (head!=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
定义节点代码
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
代码测试
public class Solution {
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
int i = 2;
ListNode node = new ListNode(1);
ListNode head = node;
while (i!=10){
node.next = new ListNode(i);
i++;
node = node.next;
}
ListNode listNode = ReverseList(head);
while (listNode!=null){
System.out.print(listNode.val+"\t");
listNode = listNode.next;
}
System.out.println();
}
public static ListNode ReverseList(ListNode node){
if(node==null||node.next==null)
return node;
ListNode head = node;
ListNode pre = null;
ListNode next = null;
while (head!=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
测试截图
输入数据 1 2 3 4 5 6 7 8 9