反转链表
题目大家都很熟悉了!
描述
输入一个链表,反转链表后,输出新链表的表头。
示例1
输入:
{1,2,3}
返回值:
{3,2,1}
java:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
}
}
c++:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
}
};
这里给两种方法:1.递归, 2.循环(原链表上修改指针所知的方向),3.还有就是遍历链表,头插法创建一个链表,4.5.6.7…
递归:
递归,就要知道函数(也就是方法,以下就叫函数了)的作用是什么,在这里,可知函数的作用是反转head指向的链表,并且返回头指针; 知道了作用,接下来就是找递归结束条件,可知,当head为空或者只有一个节点的时候,是不需要反转的,所以,当head == null或者head->next == null时,直接返回head
就可以初步写成这样:
//java版本
public class Solution {
public ListNode ReverseList(ListNode head) {
if ( head == null || head.next == null ) {
return head;
}
}
}
//c++版本
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if( !pHead || !pHead->next ) {
return pHead;
}
}
};
接下来,我们就根据函数的作用来完成接下来的操作,
我们想要翻转head指向的链表,首先就要把head->next指向的链表先翻转过来,这个能理解!!!
如下图:
那么,反转head->next指向的链表怎么做呢?根据我们已经知道的函数的作用我们可以这么写
//java版本
//这就是反转head->next指向的链表,由于最后要返回一个头指针,所以返回一个ListNode
ListNode node = ReverseList(head.next);
//c++版本
ListNode* node = ReverseList(pHead->next);
所以上图完整应该是这样的
接来下,只需要让2.next指向1(就是head)是不是就ok了。
//java
public class Solution {
public ListNode ReverseList(ListNode head) {
if ( head == null || head.next == null ) {
return head;
}
//反转head.next指向的链表
ListNode node = ReverseList(head.next);
//让2指向1
head.next.next = head;
head.next = null;
//返回node
return node;
}
}
//c++
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if( !pHead || !pHead->next ) {
return pHead;
}
ListNode* node = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next= NULL;
return node;
}
};
循环
核心步骤:
//java
public class Solution {
public ListNode ReverseList(ListNode head) {
if ( head == null || head.next == null ) {
return head;
}
ListNode p = head, q = p.next;
p.next = null;
while ( q.next != null ) {
ListNode r = q.next;
q.next = p;
p = q;
q = r;
}
q.next = p;
return q;
}
}
//c++
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if( !pHead || !pHead->next ) {
return pHead;
}
ListNode *p = pHead, *q = p->next;
pHead->next = NULL;
while ( q->next ) {
ListNode *r = q->next;
q->next = p;
p = q;
q = r;
}
q->next = p;
return q;
}
};
如果,要想知道第三种方法,可以留言,我下次一定发☺☺