数据结构:请你设计一个将线性链表进行逆置的算法。
解:单链表逆置算法一struct node{ int num;
struct node *next;}
struct node* reverse(struct node *head) //head 链表头结点
{ struct node *p,*temp1,*temp2;
if(head==NULL||head->next==NULL ) return head;
p=head->next;head->next=NULL; while(p!=NULL) //p!=NULL或p { temp1=head; head=p; temp2=p;
p=p->next;
temp2->next=temp1; //或head->next=temp1; }
return head; //返回逆置后的链表的头结点}
单链表逆置算法二
struct node* reverse(struct node *head) //head 链表头结点 {struct node *p,*temp1,*temp2;
if(head==NULL ||head->next==NULL) return head; p=head->next;head->next=NULL; while(p!=NULL) //p!=NULL或p { temp1=p->next; p->next = head; head = p; p = temp1;
}
return head; //返回逆置后的链表的头结点 }
页:
[1]