您的位置:首页 > 其它

[LintCode]35.翻转链表 ***

2017-07-13 22:48 323 查看
翻转一个链表

样例

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

第一种方法就是重新建立一个单链表newList,每次将head中的第一个结点放到newList后面。

/**
* Definition of ListNode
*
* class ListNode {
* public:
*     int val;
*     ListNode *next;
*
*     ListNode(int val) {
*         this->val = val;
*         this->next = NULL;
*     }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {
if(head==NULL){
return NULL;
}
//初始化newList,temp
ListNode *newList=new ListNode(head->val);
ListNode *temp=new ListNode(0);
//依次将list的第一个结点放到newList的第一个结点位置
while(head->next!=NULL){
temp=newList;    //保存newList中的后继结点
newList=head->next;  //将head的第一个结点放到newList中
head->next=head->next->next;//从head中删除摘除这个结点
newList->next=temp;//恢复newList中后继结点的指针

}
//原头结点应该释放掉,并返回新头结点的指针
delete head;
return newList;
}
};

第二种方法是使用三个指针遍历单链表,分别指向当前遍历到的节点、它的前一个节点及后一个节点,逐个节点进行反转。 

class Solution {
public:
/**
* @param head: The first node of linked list.
* @retur
4000
n: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {

if(head == NULL)
return NULL;

ListNode *pReversHead=NULL;//反转后头节点,原链表尾节点
ListNode *pNode=head;//遍历到的节点
ListNode *pPre=NULL;//遍历节点的前节点
ListNode *pNext=NULL;
while(pNode!=NULL){
pNext=pNode->next;
if(pNext==NULL){
pReversHead=pNode;
}

pNode->next=pPre;
pPre=pNode;
pNode=pNext;
}
return pReversHead;
}
};


第三种方法是从第2个节点到第N个节点,依次逐节点插入到第1个节点(head节点)之后,最后将第一个节点挪到新表的表尾。遍历链表然后每一个节点的下一个节点指向前面的节点。先完成一个操作
1->2 变成 2->1。如果直接把2->的元素变为1,那原本2->的元素将丢失。 故需要先保存2->的节点再进行此操作。 另外还需要一个元素记录前一个节点,即是每循环一步生成的新链表的头部。

class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {

if(head == NULL)
return NULL;

ListNode *pNode=head;//遍历到的节点
ListNode *pPre=NULL;//遍历节点的前节点
ListNode *pNext=NULL;
while(pNode!=NULL){
pNext=pNode->next;
pNode->next=pPre;
pPre=pNode;
pNode=pNext;
}
return pPre;
}
};


第四种方法是递归实现。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: