迭代
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def trainningPlan(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre, cur = None, head
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
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 trainningPlan(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = null, cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
递归
参考《算法小抄》p283内容
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def trainningPlan(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
last = self.trainningPlan(head.next)
head.next.next = head
head.next = None
return last
Java
class Solution {
public ListNode trainningPlan(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode last = trainningPlan(head.next);
head.next.next = head;
head.next = null;
return last;
}
}
牛客网上有《剑指offer》的题目训练https://www.nowcoder.com/activity/oj
一个有关此题图文并茂的博客:http://blog.youkuaiyun.com/fx677588/article/details/72357389,有助于理解递归版的代码!!!
递归版本代码的参考网址:http://blog.youkuaiyun.com/yunzhongguwu005/article/details/10350339
##Solution1:迭代版
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pReverseHead = NULL; //反序链表表头,初始化为空
ListNode* pNode = pHead; //当前结点
ListNode* pPrev = NULL; //原链表中当前结点的前一个结点,初始化为空
while(pNode != NULL){
ListNode* pNext = pNode->next;//原链表中当前结点的下一个结点
if(pNext == NULL)
pReverseHead = pNode; //若下一个结点为空,则该结点就是反序链表表头
pNode->next = pPrev;//原前一个结点变为当前结点的后继结点
pPrev = pNode;//当前结点变为前序结点
pNode = pNext;//当前结点更新
}
return pReverseHead;
}
};
##Solution2:递归版
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
//如果链表为空或者链表中只有一个元素
if(pHead == NULL || pHead->next == NULL) //链表为空直接返回,而head->next为空是递归基
return pHead;
else {
ListNode* newhead = ReverseList(pHead->next);//先反转后面的链表
pHead->next->next = pHead;//再将当前节点设置为其然来后面节点的后续节点
pHead->next = NULL; //记得赋值NULL,防止链表错乱
return newhead; //新链表头永远指向的是原链表的链尾
}
}
};