反转链表

1

#include <iostream>
using namespace std;

struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
		val(x), next(NULL) {
	}
};

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
		//不带头结点的链表
		if (pHead == NULL || pHead->next ==NULL)
		{
			return pHead;
		}
		ListNode *p,*q;
		q = p = pHead;
		//1 2 3
		ListNode *head = NULL;
		while (q)
		{
			if (head == NULL)
			{
				head = p;
				q = p->next;
				head->next = NULL;
				
			}
			else{
				p = q;
				q =	q->next;
				
				p->next = head;
				head = p;
			}
		}
		return head;
    }
};
void main(){
	ListNode *head = NULL;
	ListNode *q;
	for (int i = 1; i<= 5;i++)
	{
		ListNode *p = new ListNode(i);
		p->next = NULL;
		if (head == NULL)
		{
			head = p;
			q = p;
		}
		else{
			q->next = p;
			q = p;
		}
	}

	q = head;
	while (q)
	{
		cout<<q->val<<" ";
		q= q->next;

	}
	cout<<endl;

	class Solution s;
	q = s.ReverseList(head);
	while (q)
	{
		cout<<q->val<<" ";
		q= q->next;

	}
	cout<<endl;

	while(1);
	return ;
}

2

void reverse(struct ListNode * &p)  {
	struct ListNode *ptr,*p1,*p2;
	ptr = p;
	p1 = NULL;
	while (ptr != NULL) {
		p2 = ptr;
		ptr = ptr->next;
		p2->next = p1;
		p1 = p2;
	}
	p = p1; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值