翻转一个链表
样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
挑战
非递归
在原地一次翻转完成
递归
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
//递归
if(head == null || head.next == null){
return head;//先将头节点与最后一个节点翻转
}
ListNode r = reverse(head.next);
head.next.next = head;//头节点以外的节点所以是把next的和next.next的翻转
head.next = null;//头节点被转到最后一位 下一个为null
return r;
}
}
非递归
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
//非递归
if (null == head)
{
return head;
}
ListNode pre = head;
ListNode cur = head.next;
ListNode nxt;
while (null != cur)
{
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
// 将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head
head.next = null;
head = pre;
return head;
}
}