最基本的就是反转单链表,递归和迭代都可以实现
递归解法:从后往前反转,这是不断向新链表的尾加节点,直到结束。
/**
* 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;
}
}
/**
* 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 q = null;
while (head != null) {
ListNode p = head;
head = head.next;
p.next = q;
q = p;
}
return q;
}
}
迭代解法:从前往后反转,q指向新链表的头,head指向旧链表的头,不断向新链表的头加节点,直到结束。