逆转链表

xiaoxiao2021-02-28  85

逆转链表是面试中经常遇到的题目。 一.先看看顺序表(或线性内存)的逆转

SeqList reverse(SeqList L) { if(L!=NULL) { SeqList s; s=(SeqList *)malloc(sizeof(SeqList *)*length); int i; for(i=0;i<L->length;i++) { s->data[i]=L->data[L->length-1-i]; } for(i=0;i<L->length;i++) { L->data[i]=s->data[i]; } free(s); return L; } } 步骤: 1.分配和原来数据一样大的内存空间 2.从原来数据的末尾开始拷贝 3.利用s获得的数据对原来的数据进行覆盖,释放内存。

二、逆转链表

List Reverse(List L) { Position old_head,new_head,temp; if(L!=NULL) { old_head=L-next; new_head=NULL; while(old_head) { temp=old_head->next; old_head->next=new_head; new_head=old_head; old_head=temp; } L=new_head; return L; } } 步骤:

1.建立一个新的头结点

2.将每一个原链表的头结点反转,即原头结点指向新头结点。将指针分为两部分,一部分是已经反转的指针,另一部分未反转

3,直至原链表所有指针已反转

转载请注明原文地址: https://www.6miu.com/read-22233.html

最新回复(0)