生活随笔
收集整理的這篇文章主要介紹了
C语言链表局部反转
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// ?
// ?給定一個帶頭節點的鏈表,元素由n個整數組成。然后指定兩個數字left, right指示將給定鏈表中從left到right范圍的元素進行翻轉。最后輸出翻轉后的鏈表元素。
//例如:
//鏈表為:dummy -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
//left = 3
//right = 5
//
//
//輸出為:dummy -> 1 -> 2 -> 5 -> 4 -> 3 -> 6 -> 7
#include <stdio.h>
#include <stdlib.h>typedef struct node{int data;struct node *next;
}node,*linklist;node *startlist(node *l){//初始化單鏈表 并設置為空表l=(node *)malloc(sizeof(node)); l->next=NULL;return l;
} void creatfromhead(node *l) {//利用頭插法建立單鏈表 node *p;node *r=l;int i;scanf("%d",&i);for(int j = 0;j<i;j++){p=(node *)malloc(sizeof(node)) ;scanf("%d",&p->data);p->next=r->next;r->next=p;}
}void creatfromtail(node *l){//利用尾插法建立單鏈表node *p;node *r=l;int i;scanf("%d",&i);for(int j = 0;j<i;j++){p=(node *)malloc(sizeof(node)) ;//建立一個新結點scanf("%d",&p->data);r->next=p;r=p;}r->next=NULL;
}void out(node *l)
{// 輸出鏈表 node *p=l->next;while(p){printf("%d ",p->data);p=p->next;}
}void reverse(node *l,int left,int right){// 翻轉鏈表 node *p = l;while(left>1){//找到需要翻轉局部的最左邊的前一個結點 記為pp=p->next;left--;right--;}node *q = p->next;// 將p 后面的節點分離p->next = NULL;while(q&&right>0){//將 right-left+1 個節點通過頭插法接在p的后面 即局部反轉node *m = q;q = q->next;m->next = p->next;p->next = m;right--; } //將分離的兩個鏈表接在一起while(p->next){
// printf("%d",p->data);p=p->next; }if(q){
// printf("%d",q->data);p->next = q;}
}int main()
{node *l,*m;l=(node *)malloc(sizeof(node));//建立一個頭結點 并動態分配存儲空間l->next = NULL;creatfromtail(l);int left ,right;scanf("%d %d",&left,&right);reverse(l,left,right);out(l);return 0;
}
?
總結
以上是生活随笔為你收集整理的C语言链表局部反转的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。