题目描述
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
非递归方法:
双链表:
将原链表的节点一个个摘掉,每次占掉的节点都成为新链表的头结点:
原链表:1—>2—>3—>4—>null
新链表:null
原链表:2—>3—>4—>null
新链表:1—>null
原链表:3—>4—>null
新链表:2—>1—>null
原链表:4—>null
新链表:3—>2—>1—>null
原链表:null
新链表:4—>3—>2—>1—>null
/**
* 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 newnode = null;
while(head != null){
ListNode temp = head.next;
head.next = newnode;
newnode = head;
head = temp;
}
return newnode;
}
}
递归方法:
/**
* 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 cur = reverseList(head.next);
head.next.next = head;
head.next = null;
return cur;
}
}
层层递归,直到触发终止条件:
以此类推。