标签:class rev 保存 next list linked 代码 can def
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
链表逆转题,链表题在表头加一个头结点会比较好。第一种方法用非递归的方法,每次用tmp来保存要移动前面的结点,然后先删除tmp结点,然后把tmp结点插入到头结点后面即可。
/**
* 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) return head;
ListNode fakehead = new ListNode(0);
fakehead.next = head;
while(head.next != null) {
ListNode tmp = head.next;
head.next = tmp.next;
tmp.next = fakehead.next;
fakehead.next = tmp;
}
return fakehead.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) {
if(head == null || head.next == null) return head;
ListNode newhead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newhead;
}
}
[leetcode]206.Reverse Linked List
标签:class rev 保存 next list linked 代码 can def
原文地址:https://www.cnblogs.com/shinjia/p/9785131.html