数据结构基础内容 - 单链表
作者:
gnn
,
2023-09-21 22:23:32
,
所有人可见
,
阅读 114
单链表
struct Node {
int val;
Node *next;
Node(int x) : val(x), next(NULL) {}
};
Node *CreateListByHead(int arr[], int n)
{
Node *head = NULL;
for(int i = 0; i < n; i ++)
{
Node *node = new Node(arr[i]);
if(head == NULL)
{
head = node;
}
else{
node -> next = head;
head = node;
}
}
return head;
}
Node *CreateListWithHead(int arr[], int n)
{
Node *dummy = new Node(-1);
for(int i = 0; i < n; i ++)
{
Node *node = new Node(arr[i]);
node -> next = dummy -> next;
dummy -> next = node;
}
return dummy -> next;
}
Node *CreateListByTail(int arr[], int n)
{
Node *head = nullptr;
Node *tail = nullptr;
for(int i = 0; i < n; i ++)
{
Node *node = new Node(arr[i]);
if(head == nullptr)
{
head = node;
tail = node;
}
else
{
tail -> next = node;
tail = node;
}
}
return head;
}
Node *CreateListWithTail(int arr[], int n)
{
Node *dummy = new Node (-1);
Node *tail = dummy;
for(int i = 0; i < n; i ++)
{
Node *node = new Node(arr[i]);
tail -> next = node;
tail = node;
}
return dummy -> next;
}
Node *getNodeByIndex(Node *head , int i)
{
Node *p = head;
while(i --) p = p -> next;
return p;
}
Node *getNodeByValue(Node *head, int e)
{
for(Node *p = head; p; p = p -> next)
if(p - val = e)
return p;
return NULL;
}
void deleteNode(Node *head, int index)
{
Node *p = head;
for(int i = 0; i < index - 1; i ++)
p = p -> next;
p -> next = p -> next -> next;
}
void print(Node *head)
{
for(Node *p = head; p; p = p -> next)
cout << p - val << " ";
cout << endl;
}
int main()
{
int a[] = {1, 2, 3, 4};
int n = sizeof(a)/ sizeof(int);
Node *head = CreateListByTail(a,n);
print(head);
insertNode(head, 2, 0);
print(head);
deleteNode(head, 2);
print(head);
return 0;
}