C語言:單鏈表的反轉

  • 思路  

定義三個指針分別指向

當前結點(pte)、下一個結點(pnext)、上一個結點(pre)

從頭結點開始遍歷、每個循環內的四步爲

1.將pnext指向下一個結點(pnext=pte->next)

2.改變當前結點的指針域(pte->next=pre)

3.將pre指向當前結點(pre=pte)

4.當前結點後移、使pte指向下一個結點(pte=pnext)

循環結束後將pte->next=pre以連接上最後一個結點

  • PS

需要注意的是鏈表創建完的輸出函數(list1)和反轉後的輸出函數(list2)不一樣

list1跳過頭結點輸出

list2相當於跳過尾結點輸出

  • 代碼展示(編譯環境VS2017)
    #include<stdio.h>
    struct node
    {
    	int data;
    	struct node*next;
    };
    
    
    struct node * create(struct node *p)
    {
    	int x,n,i;
    	struct node *ph=p, *pte,*pta=p;
    	printf("請輸入結點個數:\n");
    	scanf("%d", &n);
    	printf("請輸入結點:\n");
    	for(i=0;i<n;i++)
    	{
    		scanf("%d", &x);
    		pte = (struct node *)malloc(sizeof(struct node));
    		pte->next = NULL;
    		pte->data = x;
    		pta->next = pte;
    		pta = pte;
    	}
    	return ph;
    }
    void list1(struct node *p)
    {
    	p = p->next;
    	while (p)
    	{
    		printf("%d ", p->data);
    		p = p->next;
    	}
    }
    void list2(struct node *p)
    {
    	while (p->next)
    	{
    		printf("%d ", p->data);
    		p = p->next;
    	}
    }
    struct node * reverse(struct node *p)
    {
    	struct node *pte=p, *pnext=NULL, *pre=NULL;
    	while (pte->next)
    	{
    		pnext = pte->next;
    		pte->next = pre;
    		pre = pte;
    		pte = pnext;
    	}
    	pte->next = pre;
    	return pte;
    }
    int main()
    {
    	struct node *ph;
    	ph = (struct node *) malloc(sizeof(struct node));
    	ph->next = NULL;
    	ph = create(ph);
    	printf("輸出\n");
    	list1(ph);
    	ph = reverse(ph);
    	printf("\n反轉\n");
    	list2(ph);
    	getchar();getchar();
    	return 0;
    }

     

歡迎交流!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章