单向链表
struct ListNode {// 单向链表
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
从尾到头打印链表
vector<int> TravelListFromTailToHead(struct ListNode* head) {// 【从尾到头打印链表】
vector<int> result;
if(NULL == head)
return result;
ListNode *p = head;
stack<ListNode*> nodeStack;
while(p != NULL) {
nodeStack.push(p);
p = p->next;
}
while(!nodeStack.empty()) {
p = nodeStack.top();
result.push_back(p->val);
nodeStack.pop();
}
return result;
}
链表中倒数第 k 个结点
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {// 【链表中倒数第 k 个结点】
if(NULL == pListHead || 0 == k) return NULL;
ListNode *p1 = pListHead, *p2 = pListHead;// 使用快慢指针
while(p2->next && k-- > 1) {// k-- > 1 一定要放在后面
p2 = p2->next;
}
if(k > 1) return NULL;// 说明 k 值比节点数还大
while(p2->next) {
p2 = p2->next;
p1 = p1->next;
}
return p1;
}
反转链表
ListNode* ReverseList(ListNode* pHead) {// 【反转链表】
if(NULL == pHead) return NULL;
ListNode *p = pHead, *pNext = pHead->next, *pPre = NULL;// 需要定义三个指针
while(pNext) {
p->next = pPre;
pPre = p;
p = pNext;
pNext = pNext->next;
}
p->next = pPre;
return p;
}
合并两个排序的链表
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {// 【合并两个排序的链表】
if(NULL == pHead1) return pHead2;
if(NULL == pHead2) return pHead1;
ListNode *pHead = NULL, *p;// pHead:保存新链表表头;p:用于新链表遍历生成
if(pHead1->val <= pHead2->val) {
pHead = pHead1;
pHead1 = pHead1->next;
} else {
pHead = pHead2;
pHead2 = pHead2->next;
}