大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

140 lines
2.9 KiB

#include <stdio.h>
#include <stdlib.h>
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; i<m; i++) {
next = Current->next;
// 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<n;i++){
printf("Please input the value of Node:\n");
scanf("%d",&x);
Insert(x);
Print();
}
head = Reverse1(head);
printf("Reverse linked list is:\n");
Print();
Reverse2(head);
printf("Reverse linked list is:\n");
Print();
// head = reverseBetween(head,2,4);
// Print();
// printf("Print2 linked list is:\n");
// Print2(head);
// char name[100];
// printf("What is your name?\n");
// scanf("%s",name);
// printf("Hello,%s,nice to meet you!\n",name);
}