61. 旋转链表
#include <stdio.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* rotateRight(struct ListNode* head, int k) {
if(head == NULL || k == 0) return head;
struct ListNode* node = head;
int len = 1;
while(node->next) { //先找到尾结点
node = node->next;
len++;
}
if(len == k) return head;
node->next = head; //将尾结点指到头节点
int i = len - k % len; //减少多余的循环计算
while(--i) head = head->next; //遍历寻找完尾结点,再开始遍历头节点
struct ListNode * res = head->next;
head->next = NULL;
return res;
}
先遍历找到尾结点,让尾结点指向头结点,然后根据规律发现(如果k = 2,则从倒数第二个和倒数第三个断开) 然后根据遍历头结点head指向k的前一个,再用新定义的指针指向倒数第k,这时头结点指向的是k的前一个结点,使head下一个指向NULL,最后返回新的链表。
83. 删除排序链表中的重复元素
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* deleteDuplicates(struct ListNode* head){
if(head == NULL) return NULL;
struct ListNode * node = head;
while(node->next != NULL) {
if(node->val == node->next->val) {
struct ListNode * tmp = node->next;
node->next = node->next->next;
free(tmp);
} else {
node = node->next;
}
}
return head;
}
206. 反转链表
#include <stdio.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* reverseList(struct ListNode* head){
if(head == NULL) return NULL;
struct ListNode * newHead = NULL, * tmp;
while(head) {
tmp = head->next;
head->next = newHead;
newHead = head;
head = tmp;
}
return newHead;
}