(easy)LeetCode 205.Reverse Linked List

时间:2023-03-09 20:14:34
(easy)LeetCode  205.Reverse Linked List

Reverse a singly linked list.

解法一:记录单链表每个节点的val,然后重新为单链表赋值。(取巧,仅仅是将val部分改变,原始node节点并没有改变)

代码如下:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
List<Integer> list=new ArrayList<Integer>();
ListNode p=head,q=head;
while(p!=null){
list.add(p.val);
p=p.next;
}
int size=list.size();
for(int i=size-1;i>=0;i--){
q.val=list.get(i);
q=q.next;
}
return head; }
}

运行结果:

(easy)LeetCode  205.Reverse Linked List

解法2:迭代。迭代是重复反馈过程的活动,其目的通常是为了逼近所需目标或结果。每一次对过程的重复称为一次“迭代”,而每一次迭代得到的结果会作为下一次迭代的初始值。

2.1 尾插入法。

代码如下:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode q=head.next;
ListNode r=null;
head.next=null;
while(q!=null){
r=q.next;
q.next=head;
head=q;
q=r;
}
return head; }
}

     运行结果:

(easy)LeetCode  205.Reverse Linked List

解法3:递归实现

代码如下:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode p= reverseList(head.next);
ListNode q=p;
while(p.next!=null)
p=p.next;
p.next=head;
head.next=null;
head=q;
return head; }
}

  运行结果:

(easy)LeetCode  205.Reverse Linked List