1. 题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
2. 题解思路与算法
将链表分为两部分,分别是原链表和反转后链表。每次将原链表的头节点断开,去连
接反转后链表的头节点,当原链表的节点全部取完,链表就反转完毕了。直接返回反
转后链表的头节点即可。
- 定义3个指针:pre指向反转后链表的头节点, cur指向原链表的头节点,fut指向cur所指向节点的下一节点;
- cur所指向节点的下一节点指向pre所指向节点,即原链表的头节点一直指向反转后的头节点;
- 移动pre指针到cur指针所在的位置,移动cur指针到fut指针所在位置,完成局部反转;
- 循环上述过程,直至cur指针指向null时,链表的反转完成。
3. 代码
1. C++
指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head;
ListNode *pre = NULL, *cur = head, *fut = head->next;
while(cur){
fut = cur->next;
cur->next = pre;
pre = cur;
cur = fut;
}
return pre;
}
};
递归(了解)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head;
ListNode *tail = head->next, *p = reverseList(head->next);
head->next = tail ->next;
tail->next = head;
return p;
}
};
2. Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode pre = null, cur = head, fut = head.next;
while(cur != null){
fut = cur.next;
cur.next = pre;
pre = cur;
cur = fut;
}
return pre;
}
}