反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
笨人的方法,遍历输出链表元素到列表,让后再倒序遍历列表创建新的链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
List<Integer> list = new ArrayList();
while(head!=null){
list.add(head.val);
head=head.next;
}
ListNode ansNode = new ListNode(0);
ListNode temNode = ansNode;
for(int i=list.size()-1;i>=0;i--){
temNode.next=new ListNode(list.get(i));
temNode=temNode.next;
}
return ansNode.next;
}
}
简单点的迭代,需要前置节点和当前节点地址交换
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode preNode = null;
ListNode curNode = head;
while(curNode!=null){
ListNode temNode =curNode.next;//缓存当前节点的下个元素
curNode.next=preNode;//当前节点的下个元素设置为前置元素
preNode=curNode;//前置元素改为当前节点,节点交换
curNode=temNode;//向下移动一个元素
}
return preNode;
}
}
递归方法,不是太理解,个人的理解是将得到的节点往后添加,然后将前一个节点置空
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode p = reverseList(head.next);
head.next.next=head;
head.next=null;
return p;
}
}
具体参考官方题解