1.题目要求:
给你链表的头节点 head 和一个整数 k 。
交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。
2.做题思路:
把链表中的结点存入数组中,改变数组,再把数组的值返还给链表
3.做题步骤:
1.让链表遍历一遍,创造数组:
truct ListNode* cur = head;
int count = 0;
while(cur){
count++;
cur = cur->next;
}
int* number =(int*)malloc(sizeof(int) * count);//创造存入链表的数组
2.把链表的结点存入数组中:
int j = 0;
cur = head;
while(cur){
number[j] = cur->val;
j++;
cur = cur->next;
}
3.根据题目要求,改变数组:
int i = 0;
int index = 0;
for(i = 0;i < j;i++){
if(k == i + 1){
index = i;
}
}
int index1 = 0;
for(i = j - 1;i >= 0;i--){
if(j - i == k){
index1 = i;
}
}
int temp = number[index];
number[index] = number[index1];
number[index1] = temp;
cur = head;
i = 0;
4.把数组的值存入链表,并返回
while(cur){
cur->val = number[i];
i++;
cur = cur->next;
}
return head;
}
全部代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapNodes(struct ListNode* head, int k) {
struct ListNode* cur = head;
int count = 0;
while(cur){
count++;
cur = cur->next;
}
int* number =(int*)malloc(sizeof(int) * count);//创造数组
int j = 0;
cur = head;
//把链表的结点存入数组
while(cur){
number[j] = cur->val;
j++;
cur = cur->next;
}
int i = 0;
//根据题目要求改变数组
int index = 0;
for(i = 0;i < j;i++){
if(k == i + 1){
index = i;
}
}
int index1 = 0;
for(i = j - 1;i >= 0;i--){
if(j - i == k){
index1 = i;
}
}
//把数组的值放入链表中
int temp = number[index];
number[index] = number[index1];
number[index1] = temp;
cur = head;
i = 0;
while(cur){
cur->val = number[i];
i++;
cur = cur->next;
}
return head;
}
}