先实现创建和打印链表的方法
// 链表节点
struct Node {
int data;
struct Node * next;
};
// 创建链表
struct Node* createLink(int *arr,int len){
struct Node *head = malloc(sizeof(struct Node*));
struct Node *tmp = head;
int i = 0;
while (i < len) {
struct Node * node = malloc(sizeof(struct Node*));
node->data = *(arr +i);
node->next = NULL;
head->next = node;
head = head->next;
i++;
}
return tmp->next;
}
// 打印链表
void ob_point(struct Node* head){
printf("\n");
while (head != NULL) {
printf("%d ",head->data);
head = head->next;
}
}
1、合并两个有序链表
struct Node * mergeLink(struct Node *p,struct Node *q) {
struct Node * head = malloc(sizeof(struct Node));
struct Node * tmp = head;
while (p != NULL || q != NULL) {
if (p == NULL) {
head->next = q;
break;
}
if (q == NULL) {
head->next = p;
break;
}
if (p->data < q->data) {
head->next = p;
p = p->next;
} else {
head->next = q;
q = q->next;
}
head = head->next;
}
return tmp->next;
}
2:链表倒序
struct Node * reverseLink2(struct Node *head){
struct Node * p = NULL;
struct Node * temp = NULL;
struct Node * tem_head = NULL;
while (head) {
tem_head = head;
head = head->next;
temp = p;
p = tem_head;
p->next = temp;
}
return p;
}
3:链表相交
思路一:
- 先遍历两个链表,length1 和length2
- 然后移动head指针,
- 长的链表先走,先走|length2-length1|个
- 然后一起走,比较是否一样
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode * temp_a = headA;
struct ListNode * temp_b = headB;
int a_count = 0;
while (headA != NULL) {
a_count ++;
headA = headA->next;
}
int b_count = 0;
while (headB != NULL) {
b_count ++;
headB = headB->next;
}
int dif_count = a_count - b_count;
if (a_count < b_count) {
struct ListNode * temp = temp_a;
temp_a = temp_b;
temp_b = temp;
dif_count = b_count - a_count;
}
while (temp_a != NULL) {
if (dif_count <= 0) {
if (temp_a == temp_b) {
return temp_a;
} else {
temp_a = temp_a->next;
temp_b = temp_b->next;
}
} else {
temp_a = temp_a->next;
dif_count --;
}
}
return NULL;
}
思路二:
A+B = B+A
- 一个链表,先遍历A,然后遍历B
- 另一个链表,先遍历B,然后遍历A。总长度一样
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if (headA == NULL) {
return NULL;
}
if (headB == NULL) {
return NULL;
}
struct ListNode * temp_a = headA;
struct ListNode * temp_b = headB;
int flag_a = 0;
int flag_b = 0;
while (temp_a != temp_b) {
temp_a = temp_a->next;
if (temp_a == NULL && flag_a == 0) {
flag_a = 1;
temp_a = headB;
}
temp_b = temp_b->next;
if (temp_b == NULL && flag_b == 0) {
flag_b = 1;
temp_b = headA;
}
}
return temp_a;
}