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

翻转一个链表

样例

给出一个链表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.
     * @return: 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;
    }
};

第四种方法是递归实现。。。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值