#include <stdio.h>
#include <stdlib.h>
struct linkList
{
int num;
struct linkList *next;
};
void print(struct linkList *head)
{
struct linkList *p=head;
while(p!=NULL)
{
printf("%d-",p->num);
p=p->next;
}
}
//原地反转
struct linkList *revert_self(struct linkList *head)
{
struct linkList *begin = NULL, *end = NULL;
if(head==NULL || head->next==NULL)
{
return head;
}
begin = head;
end = head->next;
while(end!=NULL)
{
//要点:要保证链表不断,一断就完!!!
//将end从链表中摘除
begin->next = end->next;
//将end移动链表头
end->next = head;
head = end;//将end置成新的链表头
//调整end的指向,让它指向begin后一个节点,为下一个节点的反转做准备
end = begin->next;
}
return head;
}
//脱壳反转(头插法)
struct linkList *revert_headinsert(struct linkList *head)
{
struct linkList *new_head=NULL,*temp=NULL;
if(head==NULL || head->next==NULL)
{
return head;
}
while(head!=NULL)
{
temp = head;
//将temp从链表中摘除
head = head->next;
//将摘除的结点插入到新链表的头部
temp->next = new_head;
new_head = temp;
}
return new_head;
}
int main()
{
struct linkList ssl[3]={{1,&ssl[1]},{2,&ssl[2]},{3,NULL}};
struct linkList *head=ssl;
printf("原链表:\n");
print(head);
// head=revert_self(head);
head=revert_headinsert(head);
printf("\n反转后的链表:\n");
print(head);
return 0;
}
反转链表(C语言)
最新推荐文章于 2024-05-04 11:49:45 发布