1.使用C語言創(chuàng)建一個(gè)鏈表:
typedef struct nd{
int data;
struct nd* next; } node;
//初始化得到一個(gè)鏈表頭節(jié)點(diǎn)
node* init(void){
node* head=(node*)malloc(sizeof(node));
if(head==NULL) return NULL;
head->next=NULL;
return head;
}
//在鏈表尾部插入數(shù)據(jù)
void insert(node* head,int data){
if(head==NULL) return;
node* p=head;
while(p->next!=NULL)
p=p->next;
node* new=(node*)malloc(sizeof(node));
if(new==NULL) return;
new->data=data;
new->next=NULL;//新節(jié)點(diǎn)作為鏈表的尾節(jié)點(diǎn)
p->next=new;//將新的節(jié)點(diǎn)鏈接到鏈表尾部
}
//從鏈表中刪除一個(gè)節(jié)點(diǎn),這里返回值為空,即不返回刪除的節(jié)點(diǎn)
void delete(node* head,int data){
if(head==NULL) return ;
node *p=head;
if(head->data==data){//如何頭節(jié)點(diǎn)為要?jiǎng)h除的節(jié)點(diǎn)
head=head->next;//更新鏈表的頭節(jié)點(diǎn)為頭節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)
free(p);
return;
}
node *q=head->next;
while(q!=NULL){
if(q->data==data){//找到要?jiǎng)h除的節(jié)點(diǎn)q
node *del=q;
p->next=q->next;
free(del);
}
p=q;//不是要?jiǎng)h除的節(jié)點(diǎn),則更新p、q,繼續(xù)往后找
q=q->next;
}
}
2.Java創(chuàng)建鏈表
創(chuàng)建一個(gè)鏈表
class Node {
Node next = null;
int data;
public Node(int d) { data = d; }
void appendToTail(int d) {//添加數(shù)據(jù)到鏈表尾部
Node end = new Node(d);
Node n = this;
while (n.next != null) { n = n.next; }
n.next = end;
}
}
從單鏈表中刪除一個(gè)節(jié)點(diǎn)
Node deleteNode(Node head, int d) {
Node n = head;
if (n.data == d) { return head.next; /* moved head */ }
while (n.next != null) {
if (n.next.data == d) {
n.next = n.next.next;
return head; /* head didn't change */
} n = n.next;
}
}