<leetCode>反转链表

写这个主要是为了自我反省,自己写的代码,执行效率不高且代码多,别人写的既简洁又省时省内存。下面就是记录了自己写的代码,和别人的代码

自己写的

用了递归的方法,每次传入链表头循环,去掉最后一个结点,时间复杂度为n的平方。没有多分配结点,仅仅多分配了一个头结点。

/** 
* Definition for singly-linked list. 
*  struct ListNode { 
*     int val; 
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* }; 
class Solution {
private:    
	int findLastNode(ListNode* head, ListNode* temp)   
	 {        
	 	ListNode *p = head;        
	 	while(p)        
	 	{            
	 		if (NULL == p->next)           
	 		{                
	 		 	temp->next = p;                
	 		 	temp = temp->next;               
	 		 	p = NULL;               
	 		 	return 0;           
	 		 }            
	 		 if (NULL == p->next->next)           
	 		 {              
		 		 temp->next = p->next;               
		 		 temp = temp->next;               
		 		 p->next = NULL;               
		 		 return findLastNode(head,temp);           
		 	 }          
		 	 p = p->next;       
		 }        
		 return 0;    
	}
public:       
ListNode* reverseList(ListNode* head) {                
	ListNode  returnList(0), *temp = &returnList;        
	findLastNode(head, temp);
        return returnList.next;   
        }
};

别人写的

//迭代法
public ListNode reverseList(ListNode head) {
    ListNode pre = null;
    ListNode cur = head;
    while(cur!=null) {
        ListNode next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    return pre;
}
//尾递归
public ListNode reverseList(ListNode head) {
    return reverse(null,head);
}

private static ListNode reverse(ListNode pre,ListNode cur){
    if(cur==null) return pre;
    ListNode next = cur.next;
    cur.next = pre;
    return reverse(cur,next);
}
// Time 8ms, 99%
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *p;
        for(p=NULL; head; swap(head,p))
            swap(p,head->next);
        return p;
    }
};

看了别人写的,再看看自己写的,像TM什么狗屎。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值