码迷,mamicode.com
首页 > 其他好文 > 详细

单链表翻转的几种写法

时间:2015-08-02 23:29:04      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:单链表   链表翻转   

	/*
	 * 带头节点
	 */
	ListNode * reverse(ListNode *head) {
		if (head == NULL || head->next == NULL)
			return head;

		ListNode nhead(-1);//头节点
		nhead.next = head;
		ListNode *prev = head;
		ListNode *next = head->next;

		while (next != NULL) {
			prev->next = next->next;
			next->next = nhead.next;
			nhead.next = next;
			next = prev->next;
		}
		return nhead.next;
	}
	
	//不带头结点
	ListNode* reverse2(ListNode *head){
		if(head == NULL || head->next == NULL)
			return head;
		ListNode *prev = head;
		ListNode *cur = prev->next;
		ListNode *next = cur->next;
		
		while(cur != NULL){
			cur->next = prev;
			prev = cur;
			cur = next;
			next = next ? next->next : NULL;
		}
		head->next = NULL;
		return prev;
	}
	ListNode *reverseList(ListNode *head) {
		ListNode *pre = NULL, *next = NULL;
		while (head) {
			next = head->next;
			head->next = pre;
			pre = head;
			head = next;
		}
		return pre;
	}


版权声明:本文为博主原创文章,未经博主允许不得转载。

单链表翻转的几种写法

标签:单链表   链表翻转   

原文地址:http://blog.csdn.net/tangchenchan/article/details/47212823

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!