单链表逆序的两种方法

单链表逆序的两种方法

typedef ElemType int;
typedef struct node
{
ElemType data;
struct node *next;
}Node;

Node *reverse(node *head)
{
Node *p, *q, *r;

if(head->next == NULL || head == NULL)
{
	return head;
}

p = head;
q = head->next;

while(q)
{
	r = q->next;
	q->next = p;
	p = q;
	q = r;
}
head->next = NULL;
head = p;

return head;

}

Node *Reverse(Node *head)
{
Node *newHead;

if(head == NULL || head->next == NULL)
{
	return head;
}

newHead = Reverse(head->next);
head->next->next = head;
head->next = NULL;

return newHead;

}

你可能感兴趣的:(数据结构与算法)