#include #include struct Node { int data; struct Node* next; }; struct Node* head; // 在链表头节点插入一个值为x的节点 void Insert(int x){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = x; temp->next = head; // if(head != NULL)temp->next = head; head = temp; } // 迭代法实现反转列表 struct Node* Reverse1(struct Node* head){ struct Node *Current,*Prev,*next; Current = head; Prev = NULL; while(Current != NULL){ next = Current->next; Current->next = Prev; Prev = Current; Current = next; } head = Prev; return head; } // 递归法实现反转列表 void Reverse2(struct Node* p){ if(p->next ==NULL){ head = p; return; } Reverse2(p->next); struct Node* q = p->next; q->next = p; p->next = NULL; } // 链表内指定区间反转 调试好了 struct Node* reverseBetween(struct Node* head, int m, int n ) { // write code here if(head == NULL)return head; if(head->next == NULL)return head; if(m == n)return head; struct Node *Current,*Prev,*next,*start,*start_last; int i; Current = head; Prev = NULL; next = NULL; // 先找到开始位置 for (i=1; inext; // Current->next = Prev; Prev = Current; Current = next; } // 标记 start_last = Prev; start = Current; // 反转 for (i=0; i<(n-m+1); i++) { next = Current->next; Current->next = Prev; Prev = Current; Current = next; } // 头尾节点重指向 if(start != head){ start->next = next; start_last->next = Prev;//start!=head的情况下,需要保留start上一个指针 } else { start->next = next; head = Prev;//start==head的情况下,直接将head指向待反转的最后一个 } return head; } //打印链表的所有值 void Print(){ struct Node* temp = head; printf("List is:"); while(temp){ printf("%d",temp->data); temp = temp->next; } printf("\n"); } void Print2(struct Node*p){ if(p ==NULL){ printf("\n"); return; } // 正序打印 // printf("%d",p->data); // Print2(p->next); // 反转打印 printf("%d",p->data); Print2(p->next); } int main(){ head = NULL; int n,x,i; printf("Please input the number of node:\n"); scanf("%d",&n); for(i = 0;i