您的位置:首页 > 其它

Reverse Linked List

2016-12-01 22:13 246 查看

Description:

Reverse a singly linked list.

问题描述:

反转链表。—-in place操作,不要新开空间

给定链表的头结点,得到反转链表的头结点。

解法一(迭代解法–尾插法)

思路:直观感觉是将链表的指向全部反向,但是要先用临时结点存储后一结点信息,以免反向后找不到后一节点,迭代之前初始化prev空结点来作为reverse后链表的头结点。每轮更新prev和head向前移动。

code:

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 prev = null;
while (head != null){
//储存后一结点信息
ListNode tmp = head.next;
//指针反向
head.next = prev;
//更新prev和head,均向前移动
prev = head;
head = tmp;
}
return prev;
}
}


解法二(递归解法)

思路:

假设链表有N个结点,先递归颠倒最后N-1个结点,然后小心地将原链表中的首结点插入到结果链表的末端

利用递归遍历到链表的尾部

code:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) return null;
if(head.next == null) return head;
ListNode second = head.next;
ListNode rest = reverseList(second);
second.next =head;
head.next = null;
return rest;

}
}


彩蛋:

这个问题在《算法》一书上有深刻阐述(P103—Q1.3.30)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 递归 迭代