题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
迭代法:
package leetcode;
public class ReverseList {
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode reverseList(ListNode head) {
ListNode next = null;
ListNode pre = null;
while(head != null) {
//定义一个temp保存链表的下一个结点,方便链表的移动
ListNode temp = head.next;
//让head指向他的前一个节点
head.next = pre;
//新的链表指向已经反转的最后一个节点
pre = head;
//将head原链表移动到下一个元素
head = temp;
}
return pre;
}
public static void main(String[] args) {
ListNode a = new ListNode(1);
ListNode b = new ListNode(2);
ListNode c = new ListNode(3);
ListNode d = new ListNode(4);
ListNode e = new ListNode(5);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
new ReverseList().reverseList(a);
while (e != null) {
System.out.println(e.val);
e = e.next;
}
}
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev = NULL;
ListNode *curr = head;
while(curr!=NULL){
ListNode *temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
head = prev;
return head;
}
};
递归法:
递归的终止步分三种情况讨论:
- 原链表为空,直接返回空链表即可。
- 原链表仅有一个元素,返回该元素。
- 原链表有两个以上元素,由于是单链表,故翻转需要自尾部向首部逆推。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL){
return head;
}
if(head->next==NULL){
return head;
}
ListNode *newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};
反转双向链表
// 反转双向链表
public class DoubleNode{
public int value;
public DoubleNode last;
public DoubleNode next;
public DoubleNode(int data){
this.value = data;
}
}
public DoubleNode reverseList(DoubleNode head){
DoubleNode pre = null;
DoubleNode next = null;
while(head != null){
next = head.next;
head.next = pre;
head.last = next;
pre = head;
head = next;
}
return pre;
}```