# 链表基本操作题

1. 链表反转，

// 3指针，原地反转

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* pre = NULL, *cur = head, *nxt = NULL;
while(cur)
{
nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
};

2. 翻转链表m到n的结点，要求一次遍历完成（leetcode92）

Node* reverseBetween(Node* head, int m, int n)
{
Node h(0);
Node* p = &h;
Node* tail;
for(int i = 1; i <= n; i++)
if(i < m) // p指向第n-1个节点位置
p = p->next;
else if(i == m) // tail指向第第n个节点，这个节点反转后处在反转部分的最后一个
tail = p->next;
else { //每次将tail后面一个节点拿出来，放在p后面，即头插法
Node* item = tail->next;
tail->next = tail->next->next;
item->next = p->next;
p->next = item;
}
return h.next;
}

3. 两个链表相加（leetcode2）

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry = 0;
while(l1 || l2 || carry)
{
int tmp = carry;
if(l1 != NULL)  tmp += l1->val;
if(l2 != NULL)  tmp += l2->val;
carry = tmp / 10;
tmp %= 10;

ListNode* next = l1 ? l1 : l2;  // 交错
if(next == NULL)  next = new ListNode(tmp); // 进位
next->val = tmp;

p->next = next;
p = p->next;

l1 = l1 ? l1->next : NULL;
l2 = l2 ? l2->next : NULL;
}
}

4. 求链表中的倒数第K个节点

————————————————

    ListNode* getKthFromEnd(ListNode* head, int k) {
for(int i = 0;i < k-1;i++)  p2 = p2->next;
while(p2->next)
{
p1 = p1->next;
p2 = p2->next;
}
return p1;
}

5. 判断两个链表是否相交 leetcode160

// 思路二
while(pa != pb)
{
pa = pa == NULL ? headB : pa->next;
pb = pb == NULL ? headA : pb->next;
}
return pa;
}

5. 头插法和输出

#include<bits/stdc++.h>
using namespace std;

typedef struct Node
{
int val;
Node* next;
Node(int _val=0):val(_val), next(NULL){}
}Node;

// 构建链表
// 头插法
{
Node* p = (Node*)malloc(sizeof(Node));
p->val = val;
}

// 遍历链表
{
while(p)
{
printf("%d ", p->val);
p = p->next;
}
}

// 逆序输出
{
{
return;
}
}

// 求倒数第k个节点
void Kth_r(Node * head, int k)
{
for(int i = 0;i < k;i++) p = p->next;
printf("p: %d\n", p->val);
while(p != NULL)
{
p = p->next;
p2 = p2->next;
}
printf("p2: %d\n", p2->val);
}

int a[] = {1, 2, 3, 4, 5}, n = 5;

int main()
{
int i = 1;
while(i < n)
{
}