單向鏈表原地反轉


如果不要求“原地”,正向遍歷原鏈表,頭插法建立一個新的單向鏈表,它就是原鏈表的逆序。

下面利用遞歸的方法將單向鏈表原地逆序。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct node{
    int data;
    struct node *next;
}NODE;

void insert(NODE **head,NODE *node){
    if((*head)==NULL){
        *head=node;
        (*head)->next=NULL;
    }else{
        //頭插法
        node->next=(*head);
        (*head)=node;
    }
}

//利用遞歸反轉鏈表
NODE* reverse(NODE *first,NODE *second){
    if(second==NULL)
        return first;
    NODE *third=second->next;
    second->next=first;
    return reverse(second,third);
}

int main(int argc,char *argv[]){
    fprintf(stdout,"Input elements by order.Input negative to exit.\n");
    int ele=0;
    NODE *head=NULL;
    //根據用戶的輸入頭插法建立單向鏈表
    while(1){
        scanf("%d",&ele);
        if(ele<0)
            break;
        NODE *node=(NODE*)malloc(sizeof(NODE));
        memset(node,0x00,sizeof(NODE));
        node->data=ele;
        node->next=NULL;
        insert(&head,node);
    }
    printf("The original link is: ");
    NODE *curr=head;
    while(curr!=NULL){
        printf("%d  ",curr->data);
        curr=curr->next;
    }
    printf("\n");
    if(head!=NULL){
        NODE *second=head->next;
        head->next=NULL;
        NODE *newhead=reverse(head,second);
        printf("The inversed link is: ");
        curr=newhead;
        while(curr!=NULL){
            printf("%d  ",curr->data);
            curr=curr->next;
        }
        printf("\n");
    }
    return 0;
}

可以很容易地把遞歸改寫成非遞歸的形式。

NODE* inverse(NODE *head){
	if(head==NULL)
		return;
	NODE *first=head;
	NODE *second=head->next;
	first->next=NULL;
	while(second!=NULL){
		NODE *third=second->next;
		second->next=first;
		first=second;
		second=third;
	}
	return first;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM