链表题目总结

单链表

单链表反转/逆序
struct Node{
int val;
Node* next;
};
请实现一个反转单链表的函数, 函数原型为:
Node* reverseList(Node* head);
给定参数是单链表的头,请返回翻转后的单链表的头。空间复杂度要求为O(1)

思路:①->②->③->*->NULL
首先考虑0个节点和1个节点的链表,此时不需反转。
其余情况我们从左至右,一条一条反转链接的方向,代码:

#include <iostream>
using namespace std;

struct Node{
    int val;
    Node* next;
};
Node* makeList(int n){
    Node* head = new Node, *p = head;
    head->next = NULL;
    head->val = 0;

    for(int i = 1; i < n; i++){
        Node* newNode = new Node;
        newNode->next = NULL;
        newNode->val = i;
        p->next = newNode;
        p = p->next;
    } 
    return head; 
}
Node* reverseList(Node* head){
    if(head == NULL || head->next == NULL){return head;}
    Node *p1 = head, *p2 = head->next, *p3;
    while(p2 != NULL){
        p3 = p2->next;
        p2->next = p1;
        p1 = p2;
        p2 = p3;
    } head->next = NULL;
    return p1;
}
void printList(Node* head){
    while(head != NULL){
        cout << head->val << " -> ";
        head = head->next;
    } cout << "NULL\n";
}
const int SIZE = int(9);// test 9 or 10
int main(){
    Node* head = makeList(SIZE);
    printList(head);
    cout << "\n"; 
    head = reverseList(head);
    printList(head);
    return 0;
} 

双链表

你可能感兴趣的:(链表,单链表,双链表)