65,210
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct stru)
struct stru
{
int num;
struct stru *next;
};
typedef struct stru pNode;
int n;
pNode *create_list();
void print_list(pNode *head);
pNode *reverse_list(pNode *head);
void main()
{
pNode *head = NULL, *newhead = NULL;
printf("Creating the list,input the num(end of string):\n");
head = create_list();
printf("The original list is:\n");
print_list(head);
newhead = reverse_list(head);
printf("\nThe new list is:\n");
print_list(newhead);
}
pNode *reverse_list(pNode *head)
{
int i;
pNode *p1, *p2, *newhead, *newp;
for (i = 0; i <= n; i++)
{
p2 = p1 = head;
while (p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (i == 0)
{
newhead = newp = p1;
}
else
{
newp = newp->next = p1;
p2->next = NULL;
}
}
return (newhead);
}
Node* LinkList_reverse(Node* head)
{
Node *preNode,*curNode,*nextNode;
if(head==NULL) return NULL;//空链表
if(head->next == NULL) return head;//仅一个元素
curNode = head;preNode=NULL;//初始化
while(curNode)
{
nextNode = curNode->next;//先记录下一个结点
curNode->next = preNode;//改变链表方向(逆置)
preNode = curNode;//将当前结点作为下一次循环的前一个结点
curNode = nextNode;//向后推移一个结点
}
return preNode;//当遍历完链表后curNode应该为空,此时preNode就是逆置后链表头(head)
}
node* ReverseList(node* head)
{
node* p=0;
node* q=head; // now q is the head of new list
while(head->next!=0) // head node is always the same, but its next node will change
{
p=head->next; // get the next node, it is the current node
head->next=p->next; // set the head->next to the next node, using in next loop
p->next=q; // make the current node pointer the head of new list
q=p; // set the q as the head of new list
}
return q; // now q is the head of new list
}
void Reverse(List & L)
{
List p=L->next; // 原链表
L->next=NULL; // 新表(空表)
while ( p )
{
// 从原链表中取下结点s
List s=p;
p=p->next;
// 插入L新表表头
s->next=L->next;
L->next=s;
}
}